This question already has answers here:
How to add new elements to an array?
(19 answers)
Closed 8 years ago.
Im a beginner to Java and I'm trying to create an array of a custom class.
Let say I have a class called car and I want to create an array of cars called Garage. How can I add each car to the garage? This is what I've got:
car redCar = new Car("Red");
car Garage [] = new Car [100];
Garage[0] = redCar;
If you want to use an array, you have to keep a counter which contains the number of cars in the garage. Better use an ArrayList instead of array:
List<Car> garage = new ArrayList<Car>();
garage.add(redCar);
The array declaration should be:
Car[] garage = new Car[100];
You can also just assign directly:
garage[1] = new Car("Blue");
If you want to create a garage and fill it up with new cars that can be accessed later, use this code:
for (int i = 0; i < garage.length; i++)
garage[i] = new Car("argument");
Also, the cars are later accessed using:
garage[0];
garage[1];
garage[2];
etc.
Related
I have 3 classes and I want to make an object in each of them to control the other
for example, I am asked to do:
Generates a model of a Candy with the specified number of candies.
I am going to do that in class B, but the Candy is in a seperate class
public Candy(String CompanyName, String ProducerName) throws TeamException{
This.CandyProducer = ProducerName;
This.CandyCompany = CompanyName;}
Now I know I can do:
Candy FirstCandy = new Candy(KitKat, Stephen);
to create an object in the class Candy.
But what I want is to have 5 objects of the class Candy.
I tried doing:
List<Candy> CandyModel = ArrayList<Candy>(numOfCandies);
but it did not work, because I can't assign the "CompanyName", and "ProducerName" for any of the candies in the ArrayList.
Any tips ?
You can use a loop to add newly created Candy objects to your list
for (int i = 0; i < numOfCandies; i++) {
CandyModel.add(new Candy("Company" + i, "Producer" + i));
}
The ArrayList constructor creates an empty list which you need to populate with objects. The parameter in the constructor is an "expected size" or "initial internal capacity" that the list will grow to but it won't make any logical difference.
also u miss new keyword while creating array list there..
Candy FirstCandy = new Candy("KitKat", "Stephen");
Candy SecondCandy = new Candy("KitKat", "Stephen");
Candy ThirdCandy = new Candy("KitKat", "Stephen");
List<Candy> CandyModel =new ArrayList<Candy>();
CandyModel.add(FirstCandy);
CandyModel.add(SecondCandy);
CandyModel.add(ThirdCandy);
an you can iterate it using listIterator or iterator somthing like this
ListIterator<Candy> itr=CandyModel.listIterator();
System.out.println("traversing elements in forward direction...");
while(itr.hasNext()){
System.out.println(itr.next());
}
This question already has answers here:
NullPointerException when Creating an Array of objects [duplicate]
(9 answers)
Closed 6 years ago.
Why won't it compile? I am trying to sort a list of school courses by one int property: courseLevel, in ascending order.
I have a class named UCFCourse with several objects courses[]. I am assigning the property values to each object while incrementing x.Here is my code in my main:
courses[x] = new UCFCourse(courseCode, courseLevel, courseHours, replaceString, eitherCourse);
This is where I added my courses[].If I print out ListOne I get a massive list containing all my courses.
List<UCFCourse> ListOne = new ArrayList<UCFCourse>();
for (int i = 0; i < courses.length; i++) {
ListOne.add(courses[i]);
}
//I added all my courses[] to a List
List<UCFCourse> ListOne = new ArrayList<UCFCourse>();
Collections.sort(ListOne, new CourseComparator());
Comparator class:
import java.util.Comparator;
public class CourseComparator implements Comparator<UCFCourse> {
public int compare(UCFCourse Course1, UCFCourse Course2) {
return Course1.getCourseLevel() - Course2.getCourseLevel();
}
}
When I initially created my object it looked like this:
UCFCourse[] courses = new UCFCourse[75];
Not sure if this bit is relevant since I added all of them into an Array list already but I want to be thorough.
Errors:
Exception in thread "main" java.lang.NullPointerException
List<UCFCourse> ListOne = new ArrayList<UCFCourse>();
<add your items to list here>
Collections.sort(ListOne, new CourseComparator());
As this code stands, you are sending a blank list to the Comparator. If you are sure you have items in the list, check that the Course1 and Course2 items being passed actually have a value. You can test quickly by taking the 'getCourseLevel()' off of them and returning the values back to the calling method.
You're just creating a new object on your ListOne variable and that variable is still empty that's why you're getting a NullPointerException.
And try to use a camel case so that you can identify your code properly.
From the code snippet you've provided I can tell you the following:
UCFCourse[] courses = new UCFCourse[75];
only creates an array full with null objects. Lopping through this array and adding each object into your ArrayList will not instantiate them.
List<UCFCourse> ListOne = new ArrayList<UCFCourse>();
for (int i = 0; i < courses.length; i++) {
ListOne.add(courses[i]);
}
The consequence is that the Comparator#compare(UCFCourse c1, UCFCourse c2) method parameters, c1 and c2, will be null, which leads to the NullPointerException.
What you need to do before adding them to the ArrayList is to create your UCFCourse objects, e.g.:
for (int i = 0; i < courses.length; i++) {
courses[i] = new UCFCourse(...);
}
This question already has answers here:
Java ArrayList copy
(10 answers)
Closed 6 years ago.
I have an array list of:
ArrayList<ItemsBean> itemsList1 = new ArrayList<ItemsBean>();
I called the data from data base and added to this Arraylist
while (items.next()) {
ItemsBean bean = new ItemsBean();
bean.setInvNo(items.getString("Invoice_Number"));
bean.setItemnNameDisplay(items.getString("Prodname"));
bean.setParentobjectid(items.getString("ParentObjectID"));
bean.setQuantityDisplay(items.getInt("Quantity"));
bean.setProdnum(items.getInt("ProdNum"));
itemsList1.add(bean);
}
Now I have new array list:
ArrayList<ItemsBean> newListitems2 = new ArrayList<ItemsBean>();
now I want to pass same data to this new array list in same activity
You can either use addAll() or try like this arraylist2 = arraylist1 .
addAll() is like below
arraylist2.addAll(arraylist1);
Hope this is helpful :)
ArrayList newListitems2 = new ArrayList(itemsList1);
ArrayList has constructor, receiving Iterable<> as argument, so you cancreate new list with values from another list. Notice, values will remain the same, ArrayList only contains references to actual objects.
This question already has answers here:
Why does my ArrayList contain N copies of the last item added to the list?
(5 answers)
Closed 6 years ago.
I have a simple class with only one String field and I have ArrayList.
When I do for loop to add some elements to ArrayList something strange happeneds.
ArrayList<MyClass> list = new ArrayList<Myclass>();
MyClass mc = new MyClass();
for(int i=0;i<someNumber;i++){
String s = new String(Integer.toString(i));
mc.setString(s);
list.add(mc);
}
After this, when I print my list, the string for every element from the list is same.
I understand that if I do list.add(new Myclass(s); works correctly but do I need to create a new instance of MyClass every time? If someNumber is large it takes too much memory. Thanks
You are re-adding the same element to the list. Try:
List<MyClass> list = new ArrayList<>(someNumber);
for(int i=0;i<someNumber;i++){
String s = new String(Integer.toString(i));
MyClass mc = new MyClass(); // create new object mc
mc.setString(s);
list.add(mc); // add the new object to the list
}
By the same object I mean the same pointer to the object, you must create new pointer (initialize new class) to add it to the list as separate instance. In this case you were setting different value in setString on the same object and multiplicating the object in the list.
You need to move the instantiation of the object mc inside the loop.
ArrayList<MyClass> list = new ArrayList<Myclass>();
for(int i=0;i<someNumber;i++){
MyClass mc = new MyClass();
String s = new String(Integer.toString(i));
mc.setString(s);
list.add(mc);
}
Following line will initialize arraylist with 9 elements with value true.
public ArrayList<Boolean> timeTable = new ArrayList<Boolean>(Collections.nCopies(9, true));
But how can i initialize arraylist of arraylist?
public ArrayList<ArrayList<Boolean>> timeTable = new ArrayList<ArrayList<Boolean>>(Collections.nCopies(9, true));
It should mean that outer arraylist has 9 inner arraylist and each inner arraylist has 9 elements with true value.
Similar to How can I initialize an ArrayList with all zeroes in Java?
But not exactly same...
Scenario is that i need to maintain a monthly list of daily timetables. Now daily timetable will have only 9 entries, so immutable is fine. But monthly list needs to be appended each month. So it can't be an arraylist.
Given this line form java docs: "Returns an immutable list consisting of n copies of the specified object"
public ArrayList<Boolean> timeTable = new ArrayList<Boolean>(Collections.nCopies(9, true));
public ArrayList<ArrayList<Boolean>> timeTableLists = new ArrayList<ArrayList<Boolean>>(Collections.nCopies(9, timeTable));
Firstly, it is recommended to use interface types wherever possible. That would make your
ArrayList<ArrayList<Boolean>> -> List<List<Boolean>>.
Then, the initialization statement would become
public List<List<Boolean>> timeTable = Collections.nCopies(9, (Collections.nCopies(9, true)));