0

(Homework:) I want to use array instead of arraylist in this situation. I have the arraylist name Employee and i have to insert data of it into the tree. I load data line by line from file. But i want to use array for the Employee not arraylist. How can i do that ? There're any ways to use array instead of arraylist in this situation. The following code is my example code for arraylist Employee. I want to change List to Employee[] how can i write the following function in style of Array.

public static void main(String[] args) {
    List<Employee> employees = read("employees.txt");

    BST bst = new BST();
    for(Employee e : employees){
        bst.insert(e);
    }

}

public static List<Employee> read(String file) {
    try {
        List<Employee> employees = new ArrayList<>();

        BufferedReader reader = new BufferedReader(new FileReader(file));
        String line;
        while((line = reader.readLine()) != null ){
            String[] arr = line.split("-");
            Employee emp = new Employee();
            emp.ccode = Integer.parseInt(arr[0]);
            emp.cus_name = arr[1];
            emp.phone = arr[2];
            employees.add(emp);
        }
        return employees;
    } catch (IOException ex) {
        Logger.getLogger(TestMusic.class.getName()).log(Level.SEVERE, null, ex);
    }
    return null;
}
Maia
  • 71
  • 1
  • 9
T3King
  • 23
  • 6
  • 3
    Why do you want to use an array? Also, what do you intend to do if a line fails to parse? Or all of the file for that matter (insufficient privileges for instance)? – fge Sep 04 '17 at 07:50
  • 1
    if you just want to return an array you can use `employees.toArray()` – Jack Flamp Sep 04 '17 at 07:51
  • If you cannot use the list at all, then you need two loops - one to count the lines, the second to parse them. – Elliott Frisch Sep 04 '17 at 07:52
  • i have my txt loading file it looks like 1-Jack-09012930 and my homework 's request is just using array, i cannot use arraylist – T3King Sep 04 '17 at 07:53
  • Yeah i know how to convert to Array but i don't want to use arraylist in this example i want to use array for the Employee – T3King Sep 04 '17 at 07:54
  • But you ARE aware that you cannot count the number of lines without reading from the file first, right? – fge Sep 04 '17 at 07:55
  • how can i do that with 2 loops can you give me an example – T3King Sep 04 '17 at 07:55
  • No i don't know that how can i fix it – T3King Sep 04 '17 at 07:56
  • 1
    You don't *have to* know the number of lines in advance: you can create an array sufficiently large to contain the data initially (assuming you know an upper bound on the number of lines); or you can resize the array once it is full (which is basically what `ArrayList` does). – Andy Turner Sep 04 '17 at 08:00
  • use `countLines(String filename)` https://stackoverflow.com/questions/453018/number-of-lines-in-a-file-in-java – EugenUngurean Sep 04 '17 at 08:01
  • 1
    Always **update** your question with such core things such as "it is a homework requirement" – GhostCat Sep 04 '17 at 08:02
  • I updated the question according the Array intention – Maia Sep 04 '17 at 08:10
  • Thanks you so much – T3King Sep 04 '17 at 08:17

6 Answers6

2

This approach is not the best one, but might solve your problem. to be used for java versions < 8. The approach is to parse the file to get no. of lines, to create the employee array, and parse again to get data of all the individual employees

public static void main(String[] args) {
   int empSize = getNumberOfEmployees("employees.txt");
   employees = new Employee[empSize]; 
   employees = read("employees.txt");

    BST bst = new BST();
    for(Employee e : employees){
        bst.insert(e);
    }

}

public static int getNumberOfEmployees (String file) {

    int totalEmp = 0;
    try {
        BufferedReader reader = new BufferedReader(new FileReader(file));
        String line;
        while((line = reader.readLine()) != null ) {
            totalEmp ++;
        }
    }catch (IOException e) {
        e.printStackTrace();
    }
    return totalEmp;
}

public static Employee[] read(String file) {
    try {

        BufferedReader reader = new BufferedReader(new FileReader(file));
        String line;
        int i=0;

        while((line = reader.readLine()) != null ){
            String[] arr = line.split("-");
            Employee emp = new Employee();
            emp.ccode = Integer.parseInt(arr[0]);
            emp.cus_name = arr[1];
            emp.phone = arr[2];
            employees[i] = emp;
            i++;
        }
        return employees;
    } catch (IOException ex) {
        Logger.getLogger(TestMusic.class.getName()).log(Level.SEVERE, null, ex);
    }
    return null;
}
Urvashi Soni
  • 279
  • 1
  • 3
  • 13
  • Thanks you a lot for your help. I can try to solve my homework now with your example. Thanks you so much. – T3King Sep 04 '17 at 08:59
1

Without giving you any code (do it by yourself ;-)):

Parse the file twice:

  1. get the number of lines, create an Array based on the number of lines

  2. parse the file again, fill the Array

And some Research (keywords BufferedReader and Array) would help you too.

Maia
  • 71
  • 1
  • 9
1

It is unclear from your requirements what you want to do in the following situations:

  • one line fails to parse;
  • cannot open the file for reading.

Here is a solution which (eww) will just ignore the unparseable entries and return an empty array if the file cannot be parsed:

public final class TestMusic
{
    private static final Employee[] NO_EMPLOYEES = new Employee[0];

    public static void main(final String... args)
    {
        final BST bst = new BST();
        for (final Employee emp: getArray())
            bst.insert(emp);
    }

    private static Employee toEmployee(final String input)
    {
        final String[] arr = input.split["-"];
        final Employee emp = new Employee();

        try {
            emp.ccode = Integer.parseInt(arr[0]);
            emp.cus_name = arr[1];
            emp.phone = arr[2];
            return emp;
        } catch (NumberFormatException | IndexOutOfBoundsException e) {
            return null;
        }
    }

    private static Employee[] getArray()
    {
        final Path path = Paths.get("employees.txt");

        try (
            Stream<String> lines = Files.lines(path);
        ) {
            return lines.map(TestMusic::toEmployee)
                .filter(Objects::nonNull)
                .toArray(Employee[]::new);
        } catch (IOException ignored) {
            return NO_EMPLOYEES;
        }
    }
}

Note how this solution does not use an intermediate list at all; instead, it makes use of the Java 8 Stream API.

What is left to do here is to handle errors... That is for you to decide :)

fge
  • 119,121
  • 33
  • 254
  • 329
  • I am not really sure that if the homework refuse the usage of `ArrayList` it will accept `Stream` ;) – AxelH Sep 04 '17 at 08:22
  • @AxelH well, "if it is not forbidden we can use it", right? :) Also, this solution avoids to read the file twice :) – fge Sep 04 '17 at 08:37
  • I hope his teacher will agree with you ! ;) Yeah, well I guess this is still stored in collection of some sort (never research on how Stream really worked to be so efficient) – AxelH Sep 04 '17 at 08:46
  • Thanks you so much it helps me a lot with my homework. – T3King Sep 04 '17 at 08:59
  • @T3King note that you can only accept one answer; pick one :) – fge Sep 04 '17 at 09:00
  • Both answers i use for example for my homework it's hard to choose one :(( – T3King Sep 04 '17 at 09:11
0

if you want to convert ArrayList to array use the following code:

Employee [] arrayOfEmpolyees = new Employee[employees.size()]
employees.toArray(arrayOfEmpolyees);
Maged Saeed
  • 1,784
  • 2
  • 16
  • 35
  • I don't want to use arraylist in this code. I want to use array for Employee. How can i do that. I want to change the List employees to Employee[] employees. And write all the function again but i don't know how to do it – T3King Sep 04 '17 at 07:58
  • you may parse the file to find the length of the array then close it, open it and parse it again to fill in data. – Maged Saeed Sep 04 '17 at 08:00
0

That is like doing a step backwards. Java collections (for example the List interface and the ArrayList implementation) have various advantages compared to "plain old" arrays.

The only real advantage of arrays is their reduced overhead - but that is only important when dealing with millions or billions of things to store in a container.

So the real answer is: don't do that. Just keep using List/ArrayList.

But in case you insist, you can of course use arrays - but then you have to add that part that makes ArrayList more convenient: you have to provide code that dynamically "grows" your array once you hit its size limit. That works like this:

  • you start with an initial array of size 100 for example
  • while populating that array, you keep track of the number of slots "in use"
  • when your code wants to add the 101st element, you "grow" the array

Growing works by:

  • creating a new array, that has like currentArray.length + 100 capacity
  • using System.arraycopy() to move all entries from the old to the new array
GhostCat
  • 137,827
  • 25
  • 176
  • 248
  • 1
    "my homework 's request is just using array, i cannot use arraylist". It's a homework exercise. – Andy Turner Sep 04 '17 at 08:01
  • @AndyTurner Thanks. That is why people shouldnt use comments to provide more information about comments. Updated my answer accordingly. – GhostCat Sep 04 '17 at 08:05
  • yeah my homework exercise make me cannot use arraylist :((( – T3King Sep 04 '17 at 08:05
  • @T3King As said: A) my answer is reworked B) dont put such information into comments - that is a **core** element in your question and should go **first** within your question text! – GhostCat Sep 04 '17 at 08:06
0

Guess the size of the array, for example by taking the size of the file and dividing by 20 (approximately the size of the line in the example you gave). Then read into the array, counting the lines. If the array is full before you have reached the end of the file, allocate a new array double the size, copy everything from the old array to the new array, replace the old array with the new array and continue the same way until done. You can look at the source of ArrayList to see an example of how it is done - basically this is what ArrayList does internally.

Jonathan Rosenne
  • 2,159
  • 17
  • 27