0

i have started coding again in java after a few years of break and im trying to refresh up a bit now, but i seem to be struggeling to create a list of lists, not a multidimensional for example i just dump all my lists in one variable, if i need list x i fetch list x and assign that to a variable for easy access rather then looping through second dimension variabel.

this is what i currently have:

package src.handlers;

import java.io.BufferedReader;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.List;


public class TextManager {
    public static void load_chapters(){
        ArrayList sections = new ArrayList();
        sections.add(read_lines("src\\chapters\\0.intro.txt"));
        sections.add(read_lines("src\\chapters\\1.hello_world.txt"));
        sections.add(read_lines("src\\chapters\\2.comments.txt"));
        sections.add(read_lines("src\\chapters\\3.variabelen.txt"));
        sections.add(read_lines("src\\chapters\\4.operators.txt"));    

        for(int x=0; x < sections.size(); x++){
            // what i attempt to do ->
            Object current_section = sections.get(x); // This gives object conversion error when assigning as List<String>
            // loop here that loops all lines  in current section.
            // cannot access  cause get function says its an object not a list?
            System.out.println(current_section.get(3));
        }
    }


    public static List<String> read_lines(String filename){
        List<String> output = new ArrayList<String>();
        // Probeer het bestand in  te lezen.
        try { // Maak buffereader aan voor het inlezen met filereader module.
            BufferedReader read = new BufferedReader(new FileReader(filename));
            String cur_line;
            // zolang er een nieuwe lijn word gevonden en deze niet null is -> output toevoegen aan output variabel.
            while((cur_line = read.readLine()) != null){
                output.add(cur_line);
            } // Sluiten  van buffer reader voor exceptions te voorkomen / latere toegang mogelijk te maken.
            read.close();
            return output; //terugave vanalle file output.
        }

        catch(Exception e)
        {
            System.err.format("Exeption occured trying to read from '%s'.", filename);
            e.printStackTrace();
            return null;
        }
    }
}

got it thanks due alex :D

    public static void load_chapters(){
        ArrayList<List<String>> sections = new ArrayList();
        sections.add(read_lines("src\\chapters\\0.intro.txt"));
        sections.add(read_lines("src\\chapters\\1.hello_world.txt"));
        sections.add(read_lines("src\\chapters\\2.comments.txt"));
        sections.add(read_lines("src\\chapters\\3.variabelen.txt"));
        sections.add(read_lines("src\\chapters\\4.operators.txt"));    

        for(List<String> section : sections){
            for(String line : section){
                System.out.println(line);
            }
        }
    }
  • Raw types are one problem here... The other one is the fact that you want to be able to easily fetch the lists, but if you store them in a `List>`, you will have to know the index of the list in the parent list or you have to check its values. **Use a `Map>` for this**... – deHaar Mar 09 '20 at 11:31

2 Answers2

1

To create a list of lists, just initialize it as so:

List<List<String>> sections = new ArrayList<>();

It's advisable to avoid using the implementation types, like ArrayList; please use interface List instead. Here's an answer for that.

And then, you could just do:

sections.add(read_lines("src\\chapters\\0.intro.txt"));
// ... and so on

When iterating through the list, I recommend using the for-each loop:

for (List<String> section : sections) {
    System.out.println(section.get(3));
}

But, if you still want to use the index approach (although not recommended when iterating through Java lists), here's the code for that:

for (int x = 0; x < sections.size(); x++) {
    List<String> current_section = sections.get(x);
    System.out.println(current_section.get(3));
}

Not related to your question, but some notes on the naming conventions:

  • variables and method names should be mixedCase (or lowerCamelCase)
    • the current_section variable should be renamed as currentSection
    • the read_line and load_chapters methods I would rename them as readLine and loadChapters.
Alexandru Somai
  • 1,395
  • 1
  • 7
  • 16
  • Thankyou exactly what i wanted :D – PythonNoob Mar 09 '20 at 11:32
  • Also: thanks for iteration tip, my java is pretty rust didnt know you could iter that way much easier :) coded only 2-3 years and that was 10years+ ago when info was still scarse. – PythonNoob Mar 09 '20 at 11:40
  • Another offtopic: isnt mixed/camel case for classes ? i use as naming convention: _globalvar, normalvar, Class, function_name – PythonNoob Mar 09 '20 at 11:46
  • 1
    For classes it's **upper** camel case, like `class MyClass`. Your class name `TextManager` is correct. Check the article I've posted. Usually that's the rule of thumb for naming in Java, but you could use what you like. – Alexandru Somai Mar 09 '20 at 11:47
0

1) The first thing that I would point out is that you are working with a raw ArrayList, since Java 1.5 we got Generics, so instead of working with casted Objects you can now work with objects from the class that you want, like you did in your read_lines(String) method

ArrayList<ArrayList<String>> sections = new ArrayList<>();
// etc.
for(int x=0; x < sections.size(); x++){
    ArrayList<String> current_section = sections.get(x);
    System.out.println(current_section.get(3));
}

2) Also it is a good practice to declare variable by their interfaces, instead of the concrete implementation, so the code above would be something like:

List<List<String>> sections = new ArrayList<>();
// Depending on your needs you could change your List<> implementation like:
// List<List<String>> sections = new LinkedList<>();
// List<List<String>> sections = new Vector<>();
// etc.
for(int x=0; x < sections.size(); x++){
    List<String> current_section = sections.get(x);
    System.out.println(current_section.get(3));
}

3) But if you decide to continue working with your current code (raw ArrayList) you should make a small change because you are trying to access a method available only on the ArrayList class. To accomplish what you want you would need to to a cast to get the value from your current_section object.

for(int x=0; x < sections.size(); x++){
    ArrayList current_section = (ArrayList)sections.get(x); // CAST
    System.out.println(current_section.get(3));
}
Paullus Nava
  • 70
  • 2
  • 9