0

Hi I have two Java Files as below:

            case 6:  
                System.out.println("List All Property Details For Rent >>>");
//              System.out.println(Arrays.toString(Property_list));
                int i=0;
                while(i<count){
                    ppty.property_list[i].viewPropertyDetails("RENT");
                    i++;
                }
                System.out.println("++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
                break; 

        }

    }




    }

}

Guys, This is basically an array of properties, and a Menu to do some operation with the list. I was planning to improve my code with a java ArrayList, because its more dynamic in nature. Could anyone tell me how I can convert this array (property_list) into an ArrayList? What are the changes do I need to make? Thanks in advance.

vellattukudy
  • 789
  • 2
  • 11
  • 25

1 Answers1

1

Your commented code is perfectly valid for initiliazing the arrayList.

ArrayList<Property> property_list = new ArrayList<Property>();

In java 7 or later you don't need to specify the second Property:

ArrayList<Property> property_list = new ArrayList<>();

Unlike the java Array you don't use bracket notation to access your variables you use .get(int index):

ppty.property_list.get(count)

To add a value you use .add(Object item);

ppty.property_list.add(new Property());

And you don't need to remember the size of ArrayList by storing it in a variable. The ArrayList has the .size() method which returns the number of elements in it.


Extra tips:

  • Here you can find extra methods the ArrayList has https://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html
  • You have setters and getters in your Property object. You could set the member variables to private and use them.
  • You should replace that ppty method with the constructor method like so:

    
    public Property(int streetno,String streetname,
                String suburb,
                int postalcode,String contactperson,
                String office,int phonenumber,
                String openTime,String propertytype,
                double price, String date){
                    this.StreetNumber = streetno;
            this.StreetName=streetname;
            this.Suburb=suburb;
            this.PostalCode=postalcode;
            this.ContactPerson=contactperson;
            this.PhoneNumber=phonenumber;
            this.Office=office;
            this.OpenTime=openTime;
            this.PropertyType=propertytype;
            this.PropertyPrice=price;
            this.Date = date;
    
    
    }
    

  • This property_list should not be inside your Property object. This is something you should handle outside the object. For example in your public void displayMenuPanel() you could say ArrayList<Property> properties = new ArrayList<>(). If you put the list inside the object then it is tied with that object. If the object goes, the list goes.