Java ArrayList - can't read back properties of objects -


i want able make array list of objects, , able edit , read simple properties of each object. in case, string (colour) , integer (x). can't seem make simple code below work. note aware people use <> notation array lists, have read should possible without, , @ moment new java , wish keep things simple possible.

at moment error on line commented out (cannot find symbol x)

import java.util.arraylist;  public class arraylist_of_objects {   public static void main(string[] args)     {          arraylist al = new arraylist();          for(int =0;i<5;i++)         {             myobj ob1 = new myobj();             ob1.x = + 5;             al.add(ob1);             //system.out.println("x: "+al.get(i).x);         }         for(int j=0;j<5;j++)         {system.out.println("x: "+al.get(j).x);}          al.get(3).x=4;         al.get(3).colour="orange";         system.out.println(al.get(3).x);         system.out.println(al.get(3).colour);   }   }  class myobj {     int x;     string colour; } 

yes, need use generics kind of object in list:

arraylist<myobj> al = new arraylist<myobj>(); 

otherwise compiler doesn't know al.get(3) meant return myobj rather anything. code, not fix get calls - stop accidentally adding objects of inappropriate types list.

also, it's preferred declare variables appropriate interface type, such as:

list<myobj> al = new arraylist<myobj>(); 

(there times need concrete type, prefer programming interfaces.)

generics massive topic, tutorial linked @ start of answer should going. java generics faq great resource finding out more.


Comments

Popular posts from this blog

ios - iPhone/iPad different view orientations in different views , and apple approval process -

java Extracting Zip file -

C# WinForm - loading screen -