Accessing methods of objects stored in an ArrayList


DevX Home    Today's Headlines   Articles Archive   Tip Bank   Forums   

Results 1 to 11 of 11

Thread: Accessing methods of objects stored in an ArrayList

  1. #1
    Join Date
    May 2005
    Posts
    22

    Accessing methods of objects stored in an ArrayList

    Title basically says it all...

    I've got a class and a class nested inside that one, the outer class has an ArrayList object that stores objects of the nested class, and the objects of the nested class have their own ArrayList objects, and need to access/retrieve members of the inner classes' ArrayList objects, but don't know how.

    Now the code, then more clarification.

    Code:
    class ClassList
    {	
    
    	class Student
    	{
    		private String name;
    		private ArrayList grades;
    		private double mean;
       
    		public Student(String n, int g1, int g2, int g3, int g4)
    		{
    			name = n;
    			grades = new ArrayList();
    			grades.add(new Integer(g1));
    			grades.add(new Integer(g2));
    			grades.add(new Integer(g3));
    			grades.add(new Integer(g4));
    		}
    	}
    
    	private ArrayList students;
    	private int studentCount;	
    	private ArrayList testMean;
    	private int testCount;
        	private double classMean;
    
    	public ClassList()
    	{
    		students = new ArrayList();  
    		testMean = new ArrayList();
    		studentCount = 0;
    		testCount = 4;          
    	}
    
    /*
    Assorted blank method stubs that will be filled in with accessing and setting commands, once I figure out how to access the inner array values.
    
    Also a method that reads a .txt file and populates the ClassList arrayList of students and the student ArrayList of grades with values.
    */
    }
    Okay. So each ClassList has an ArrayList of students, and each student has an ArrayList of grades.

    I can access each student object in the classList ArrayList, but I can only retrieve its memory address. I do not know how to access any values of the student objects' ArrayLists (which are stored in the ClassList arrayList and must be accessed from there).

    Final attempt at explaining the problem: How the heck would I retrieve all the grades of a given student knowing only its index in the ClassList ArrayList?

    Any help would be much appreciated. Thanks in advance.
    Last edited by Gengar003; 05-09-2005 at 10:36 AM.

  2. #2
    Join Date
    Nov 2004
    Location
    Norway
    Posts
    1,560

    Is this what you mean ?

    Code:
    import java.util.*;
    
    public class ClassList {
    
      class Student {
        private String name;
        private ArrayList grades;
        private double mean;
        public Student(String n) {
          name = n;
        }
        public Student(String n, int g1, int g2, int g3, int g4) {
          name = n;
          grades = new ArrayList();
          grades.add(new Integer(g1));
          grades.add(new Integer(g2));
          grades.add(new Integer(g3));
          grades.add(new Integer(g4));
        }
        public ArrayList getGrades() {
          return grades;
        }
        public String getName() {
          return name;
        }
        public String toString() {
          String s=name;
          for (int i=0; i<grades.size(); i++) {
            s += " g"+(i+1)+":"+grades.get(i).toString();
          }
          return s;
        }
        public boolean equals(Object ob) {
          Student st=(Student)ob;
          return this.name.equals(st.getName());
        }
      }
    
      private ArrayList students;
      private int studentCount;
      private ArrayList testMean;
      private int testCount;
      private double classMean;
    
      public ClassList() {
        students = new ArrayList();
        students.add(new Student("John",2,3,4,5));
        students.add(new Student("Paul",9,9,9,9));
        students.add(new Student("Mary",2,3,2,3));
        // list
        System.out.println("ClassList");
        for (int i=0; i<students.size(); i++) {
          System.out.println(students.get(i));
        }
        // get a named student (utilizes the equals method of Student)
        int ix=students.indexOf(new Student("Paul"));
        Student st=(Student)students.get(ix);
        System.out.println("\n\nStudent: "+st.getName());
        ArrayList list=st.getGrades();
        System.out.println("Grades:");
        for (int i=0; i<list.size(); i++) {
            System.out.println(" g"+(i+1)+":"+list.get(i).toString());
          }
      }
      public static void main (String [] args) {
        ClassList cl=new ClassList();
      }
    }
    eschew obfuscation

  3. #3
    Join Date
    Feb 2004
    Posts
    541
    I don't know if you know some of this already, but i'll explain it anyway to make the answer more complete. There are two fundamentally different sorts of variable in Java, Primitive types and Object types.

    Primitive types are things like int and double, they have no methods or structure and are just a value.

    Object types have a structure (which you define when you write a .java file), with methods that you can call. The most basic object type in Java is the class Object. All other object types in Java extend this class. The compiler will do this for you at compile time so you may not even realise it is happening.

    Now with an ArrayList, the general idea is that it should be able to store any object. The only way to make this possible is to have it store objects of the type Object. Since all objects extend the class Object, the ArrayList can store any type of object you can define.

    The problem is that when you come to retrieve your own objects from the ArrayList they come back as type Object. You can only access the methods that were inherited from the Object class. To be able to access the other methods in your class you have to tell Java what type it is. This is known as casting. This is done by writing the type of the object in brackets before you call the method to get the object from the ArrayList....
    Code:
    Student aStudent = (Student) someArrayList.get(someIndex);

  4. #4
    Join Date
    Nov 2004
    Location
    Norway
    Posts
    1,560
    Yes indeed, and when the class in the list implements the toString method defined
    for class Object you can do

    System.out.println(aList.get(i));
    eschew obfuscation

  5. #5
    Join Date
    Feb 2004
    Posts
    541
    All classes implement toString(), it is defined in Object. Of course the implementation given in Object isn't all that useful usually

  6. #6
    Join Date
    Nov 2004
    Location
    Norway
    Posts
    1,560
    Well, what I meant was that the collection classes that return Object pointers can
    be printed like I showed above. The Object implementation of toString returns the
    pointer value and should really just be regarded as a "placeholder" for custom
    classes use. The same goes for the methods: equals, clone, toString and hashCode, and as placeholders they can be quite useful. E.g. with a
    proper override of the equals method and ArrayList can be used (almost) as a
    hashtable.
    eschew obfuscation

  7. #7
    Join Date
    May 2005
    Posts
    22
    When I try to use the type-casting method, I get a classCastException runtime error.

    @mike: Yes, I know of the distinction between objects/simple data types.

    When set up, the array structure would be as such:

    ArrayList classlist
    -Student s1
    --ArrayList grades
    ---grade 1
    ---grade 2
    ---grade 3

    -Student s2
    --ArrayList grades
    ---grade 1
    ---grade 2
    ---grade 3


    Etc.

    What I need to be able to do is, for any given index X, get that student from the classlist and access not only the student object's methods/variables, but also the methods/data of the grades array list.

    Thanks again

  8. #8
    Join Date
    Nov 2004
    Location
    Norway
    Posts
    1,560

    I fail to see the problem :(

    In my code above you see this:
    Code:
    Student st=(Student)students.get(ix);
    System.out.println("\n\nStudent: "+st.getName());
    ArrayList list=st.getGrades();
    right ?, now if i want to say, add a grade to the students
    gra list, instead of reading the name

    Code:
    Student st=(Student)students.get(ix);
    ArrayList list=st.getGrades();
    list.add(new Integer(19)); // a new grade added to list
    So if the grade was a class: Grade you would do

    Code:
    Student st=(Student)students.get(ix);
    ArrayList list=st.getGrades(); // list of Grade object
    Grade aGrade=(Grade)list.get(0);  // fix grade at position 0
    aGrade.setPassed(true);  // ... like

    I can't get it simpler than this, sorry,
    eschew obfuscation

  9. #9
    Join Date
    May 2005
    Posts
    22
    Quote Originally Posted by sjalle
    Code:
    Student st=(Student)students.get(ix);
    ArrayList list=st.getGrades();
    list.add(new Integer(19)); // a new grade added to list
    There we go. That's what I was looking for; thank you very much.

  10. #10
    Join Date
    Dec 2004
    Location
    San Bernardino County, California
    Posts
    1,468
    Remember that if you are using Java 1.5, you can use a "generic" typing to your ArrayList, so that your student list will be ArrayList<Student> and your grade list will be ArrayList<Grades>, or whatever, so that you don't have to cast in the manner of sjalle's first line of code ...

    In fact, if you are using 1.5, the compiler will complain about use of unchecked collections and prompt you to compile with -Xlint ...

  11. #11
    Join Date
    Nov 2004
    Location
    Norway
    Posts
    1,560
    if you are using Java 1.5, you can use a "generic" typing to your ArrayList
    I know, but my JBuilder 8 can't (yet) cope witj 1.5, and I'm not moving to Eclipse or
    whatevver
    just for that.... and two more things; A "typecast" is still being done,
    - but you don't have to see it with 1.5.
    If I make an arrayList and I'm just going to use it to, say return, a set of values then
    if I'm using 1.5 I'll have to use the 1.5 syntax for declaring it, but I don't have to do
    the:
    Valueclass aValue=(Valueclass)list.get(i).

    So, the only thing, in my opinion, that is gained from this is that the compiler will give
    a compile time error when the programmer (?) has forgotten what he initially stuffed into his collection.

    Another thing is that the untyped collections are useful in the cases where it is
    practical to store both eggs and bacon in the same place.

    And the other stuff, e.g. the enumerations, jadajada..
    I wish that the java-language developers would come up with some more "real"
    progress instead of things that, to me, just looks like wrappers around coding that for
    some reason is considered "nitty gritty".

    How about operator overloading ? That would really be something. I mean, its
    been there always for the String class. The OOP ayatollas may get their nickers in a
    twist over this proposal but who cares ?, not me.
    Last edited by sjalle; 05-15-2005 at 06:25 AM.
    eschew obfuscation

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center
 
 
FAQ
Latest Articles
Java
.NET
XML
Database
Enterprise
Questions? Contact us.
C++
Web Development
Wireless
Latest Tips
Open Source


   Development Centers

   -- Android Development Center
   -- Cloud Development Project Center
   -- HTML5 Development Center
   -- Windows Mobile Development Center