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());
}
Related
I have 2 classes in Java. One is a Car class that consists of 5 variables. Among them I have a List equipment variable. Another class contains the list of the Car class objects: List carlist.
My task is: I have to sort the list of car object, using Streams in Java based on the amount of the equipment items that the given car have.
How do I do that? I tried to build a separate method to count the items on the list of the object - but then within the Comparator I can't place an Object as an argument of this method.
Here's an excerpt of my code:
private int countEquipmentItems (Car s){
if (s == null){
return 0;
}
int countEquipment = 0;
List<String> a = s.getEquipment();
for (int i = 0; i <a.size() ; i++) {
countEquipment ++;
}
return countEquipment;
}
And I have tried to use this method within the Stream:
public void sortbyEquipment (List<Car> carList){
carList.stream()
.sorted(Comparator.comparing(countEquipmentItems(Car s)));
}
}
I appreciate any help
You don't need that countEquipmentItems method to count the amount of equipment. Just use car.getEquipment().size():
public void sortbyEquipment (List<Car> carList){
carList.stream()
.sorted(Comparator.comparing(car -> car.getEquipment().size()))
...
}
Of course, you can pass that Comparator directly to Collections.sort(), which will sort the list without having to create a Stream.
Your countEquipmentItems method is redundant and completely unnecessary.
Another solution to what Eran has provided would be to call the default sort method that is available for the List<T> type.
carList.sort(Comparator.comparingInt(car -> car.getEquipment().size()));
or if you want the sorted items to be in a new collection then you can do:
List<Car> clonedList = new ArrayList<>(carList); // clone the carList
clonedList.sort(Comparator.comparingInt(car -> car.getEquipment().size()));
Well, I'm new to List I've always worked with Arrays, now I'm writing a program where I cannot tell the size of the array before it's creation so I'm using List. The thing is that I've a method that returns a List of none repeating digits.
Here is my method:
public static List<Integer> arrayOfNoneRepeatingDigits(int limit) {
List<Integer> list = new ArrayList<Integer>();
for(int i = 0; i < limit; i++){
boolean ignore = false;
for(int j = i; j > 0; j/=10){
if(ignore == true) break;
for(int k = j/10; k > 0; k/=10){
if(j%10 == k%10){
ignore = true;
break;
}
}
}
if(ignore == false)list.add(i);
}
return list;
}
First my method datatype was an Array but after I changed it to List this line of code gave an error:
List<Integer> list = new List<Integer>();
I've searched online and It turned out that I should replace List with ArrayList. I did it and the error is gone now but I don't know why.
Interfaces cannot be instantiated, so no new List<Integer> stuff. Interfaces's methods don't have implementations. The implementations of those methods are in the subclasses. ArrayList is one of the subclasses of List so that's why you can use your first code snippet.
If you write new List<Integer>, it doesn't make sense. Because List's methods don't have implementations so when you call the add method, how would the compiler know what implementation is in the method?
This:
List<Integer> list = new List<Integer>();
doesn't make sense since you're trying to directly instantiate an interface, something that is not concrete and thus something that you can't do unless you create an anonymous inner class with the instantiation, something that you really don't want to do. The best solution: stick with the ArrayList for the concrete implementation (or LinkedList depending on your requirements). e.g.,
List<Integer> list = new ArrayList<>();
Out of curiosity, what motivated you to make this change when you already had working code?
List is an interface. It means there is no attribute in List, and methods are declared but not defined. So, there is not enough information to instantiate it and an error occurs. This happens same when you try to instantiate an object of an abstract class.
You can declare an object of interface/abstract class, but you cannot instantiate it. So you have two choices.
List<Integer> list = new ArrayList<Integer();
((ArrayList)list).method();
//cast it into ArrayList.
//If you try to cast a wrong class, then the error will be printed out.
This way need extra casting. Else, you can declare with ArrayList also.
ArrayList<Integer>list = new ArrayList<Integer>();
List<ArrayList<Planet>> NAME = new ArrayList<ArrayList<Planet>>(N);
List<List<Planet>> NAME = new ArrayList<ArrayList<Planet>>(N);
ArrayList<ArrayList<Planet>> NAME = new ArrayList<ArrayList<Planet>>(N);
I can't tell what's the difference of these three expressions. I realized later that maybe List is for declaration because its an interface while ArrayList could be used for initiation, as it is a class. I took the first syntax in my project and find
found : java.util.ArrayList>
required: java.util.ArrayList>
List<List<Planet>> Name = new ArrayList<ArrayList<Planet>>(N);
I have added at the header.
import java.util.ArrayList;
import java.util.List;
In another place, while I am adding Planet Object into the ArrayList:
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
if (i == j) continue;
NAME[i].add(planets[j]);
}
}
The compiler reports,
array required, but java.util.ArrayList> found
planetsForNetForceSetting[i].add(planets[j]);
Could anybody tell me the reason for this?
You are trying to retrieve data from given position of a List like an Array here: NAME[i].add(planets[j]);, what cannot be done.
To get data from an ArrayList you must use get(int) method. In thi way: NAME.get(i) instead NAME[i].
Then, your method must be
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
if (i == j) continue;
NAME.get(i).add(planets[j]);
}
}
About difference of three expressions, and why use interface to declare List<Object> list = new ArrayList<Object> instead of the class itself, look at this question.
First List<T> is a java interface parametrized by type T. ArrayList<T> is specific implementation of interface List<T>. So you may assign List<Integer> list = new ArrayList<Integer>(); This way variable list will have type List<Integer> which will hide specific implementation ArrayList<T>.
Then following lines:
List<ArrayList<Planet>> planetsList = new ArrayList<ArrayList<Planet>>();
creates variable planetsList of type List<ArrayList<Planet>> which is list of array lists. Where actual outer lists implementation is ArrayList<ArrayList<Planet>>.
List<List<Planet>> planetsList2 = new ArrayList<ArrayList<Planet>>();
Will not compile, since you cannot assign ArrayList<ArrayList<Planet>> to List<List<Planet>> Refer to this question to more deep explanation why Why can't you have a "List<List<String>>" in Java?
ArrayList<ArrayList<Planet>> planetsList3 = new ArrayList<ArrayList<Planet>>();
Will create variable planetsList3 with type ArrayList<ArrayList<Planet>>.
You need to import both java.util.List and java.util.ArrayListtypes since you are directly referencing them in your code.
And finally. You cannot assign item to list's index by array indexing syntax items[index]=item; since List<ItemType> items; is an interface not an array. These are totally different things in java.
Out of your 3 expressions, in same order as you mentioned, 2nd one is the most generic one, then 1st and then 3rd.
Which means that when you use List<Planet> listObj then you can use listObj to point to any implementation of List interface. While when you do ArrayList<Planet> listObj then you can use listObj to point to only an object of type ArrayList
Whether 1 dimensional or N dimensional, this hold true.
A more generic type and preferred one would be use of List<Object> listObj, which means that you can use listObj to point to any implementation of List interface, ALSO you in the list you can put any object. When you use List<Planet> listObj then you can only put Planet objects.
For your compile problem, your code is not sufficient to figure out root cause because I cannot see whats planetsForNetForceSetting, but just make sure that you are putting right objects in right place. Like I explained above.
Hope this helps!!!
I am only in my 8th week of Java, so I am quite new.
I have a class that has an ArrayList object, list. I have another class called TransactionCalc. I would like for TransactionCalc to have its own ArrayList object, called arr3. I need to have be exactly as large as list. I know how to declare an ArrayList that is a size other than 10, but how do you do this if you do not yet know the exact size? Is it possible?
public class TransactionCalc extends CalculateAbstract{
private int count = 0;
private ArrayList <ItemAttribute> arr3 = new ArrayList <ItemAttribute> (1);
//the 1 needs to be list.size() ??
I am assuming that in the other class I will need to do public static final int = list.size(), but is it possible to get that constant over to the TransactionCalc class so that it can be in the declaration?
I forgot to add this... since the functionality of arrayList is not really needed, I could also do list.toArray(arr3) but that still wouldn't allow for it to be an object of the TransactionCalc class. Is it possible to do that? I'd like to avoid sending the same arr3 over and over again to multiple methods in the same class.
Also, how would I put this as a constructor?
EDIT with help from amaleemur____________
I have updated my code to have:
public class FindItemInfo implements InterfacePrint{
ArrayList <ItemAttribute> list = new ArrayList<ItemAttribute>();
//load arraylist and do something with it
//sort arraylist
public void printPriority(){
TransactionCalc finish = new TransactionCalc();
for (int i = 0; i < list.size(); i++){
for (int x = 0; x < list.size(); x++){
if(arr2.get(i) == list.get(x).getPriority()){
finish.cashOut(list.get(x), bankAccount, list.size());
} //send sorted arr2 to TransactionCalc class
}
}
public static int getListSize(){
return list.size();
}
}
public class TransactionCalc {//extends CalculateAbstract{
private int count = 0;
//private ArrayList <ItemAttribute> arr3 = new ArrayList <ItemAttribute> (FindItemInfo.getListSize());
private ItemAttribute[] arr3 = new ItemAttribute[FindItemInfo.getListSize()];
public void cashOut (ItemAttribute item, double bankAccount, int size) {
//ItemAttribute[] arr3 = new ItemAttribute[size];
double runningTotal = 0;
if((runningTotal + (item.getQuantity()*item.getPrice()))<= bankAccount){
runningTotal += item.getQuantity()*item.getPrice();
bankAccount -= runningTotal;
System.out.format("You will spend $%.2f on " + item.getQuantity() + " of "+ item.getDescription(), runningTotal);
System.out.format(" and have $%.2f left to spend\n", bankAccount);
}
else{
arr3[count] = item;
count++;
}
}
I am making arr3 an object of the TransactionCalc class because it is used for a few methods. The purpose of the array/arraylist is to collect the items that are not being printed. I can use either an array or an arraylist. I initially went with an array but then didn't know the size.
I am now getting static and non-static errors. When I go to try and fix this, it causes more problems.
The neat thing about using an ArrayList is that you don't have to declare a size.
so this is sufficient and you can add items to the array list.
private ArrayList <ItemAttribute> arr3 = new ArrayList <ItemAttribute>();
in order to get the size of list, I would suggest doing this:
In your class that contains the ArrayList list, create a method
public int getListSize(){
return list.size();
}
and now you can safely access the size of list. Does this help?
so now you'd do this:
private ArrayList <ItemAttribute> arr3 =
new ArrayList <ItemAttribute>(otherClass.getListSize());
where otherClass is a placeholder for the name of your other class with the ArrayList list.
ArrayList is a mutable collection type. This means (in this case) that instances of ArrayList may host arbitrary amounts of elements and in particular, the contained elements of a given instance of ArrayList may change at runtime. So you do not have to declare the amount of elements. In typical cases, you will most likely want to use the default c'tor (=not specify the initial amount of elements). Specifying the initial amount if elements may be a good idea (performance-wise), if you know that there will be a large number of objects inserted at run-time. In such cases, initialising an instance of ArrayList may safe some memory allocations an memcopy operations.
I have a 2D ArrayList. The ArrayList contains 10 ArrayLists. I tried the following code:
This is the main 2D ArrayList. Inside the main ArrayList there are10 ArrayLists:
ArrayList<ArrayList<Items>> arrayList = new ArrayList<ArrayList<Items>>();
Here I tried to create a copy of one of the ArrayList (selectedRow is just a number which says which ArrayList I get)
ArrayList<Items> newList = new ArrayList<Items>(arrayList.get(selectedRow));
After that I create another ArrayList:
ArrayList<Items> changeList = new ArrayList<Items>(it.returnTheNewArrayList(newList,randomItem));
Then in another class I created this method. The purpose of this method is to change an attribute of one of the objects.
public ArrayList<Items> returnTheNewArrayList(ArrayList<Items> a,int item){
int randomBin = r.nextInt(50);
for(Items i:a){
if(item==i.itemIds()){
while(randomBin==i.bins()){
randomBin = r.nextInt(50);
}
i.setBin(randomBin);
}
}
return a;
}
Finally, I set the new ArrayList in the 2D ArrayList
arrayList.set(whichList, changeList);
This is the procedure. I have find out, that when I run this procedure, both newList and changeList are the same. In both of these ArrayLists I'm saving the change I did in the method returnTheNewArrayList (I found out it with the debugging). But I want to change only one (the changeList).
What did I do wrong?
The lists contain references to objects. When you call i.setBin(...) that's (presumably) making a change to the object itself.
Each list has an independent copy of the references - so you could remove an element from one list without affecting the other - but they're only references.
Imagine you gave two people clipboards, with the same list of home addresses on. One person went and painted the front door of every house list on their clipboard red, then the second person visited all the same houses. The second person would see red doors, wouldn't they? It's the same thing here. The lists contain references, not objects.
If you want the lists to be completely independent, you'll need to populate them with references to different objects.
EDIT: I've just noticed that you'll also need to change your returnTheNewArrayList method, which actually isn't even creating a new ArrayList in the first place!
public ArrayList<Items> returnTheNewArrayList(ArrayList<Items> a,int item) {
// Stuff which doesn't change the value of a...
return a;
}
Again, the value of a is just a reference to the list... so when you return the same reference back, you're not returning a new ArrayList at all.
You really need to understand how references and objects work in Java - it's absolutely crucial to working with the language.
Inside of the returnTheNewArrayList method, you first need to clone a. Otherwise you will be modifying the original ArrayList and the original Items. Jon did a nice job of explaining why, so I won't go into it here. Your code could look something like:
ArrayList<Items> clone = new ArrayList<Items>(a.size());
for(Items item: a) clone.add(item.clone());
//modify clone here
return clone;
Since you've written the Items class yourself, you will need to implement the Cloneable interface yourself.
See the clone method's wikipedia page for more information.
The newList and changeList are not the same (not == ) but their content are identical.
Your "Item" objects are passed by reference that's why the two lists references the same Items.
To get a brand new reference you should create a new instance of Item in method returnTheNewArrayList (10 new instances for 10 new references.)
public ArrayList<Items> returnTheNewArrayList(ArrayList<Items> a,int item){
//create a new List
ArrayList<Items> newList = new ArrayList<Items>();
int randomBin = r.nextInt(50);
for(Items oldItem:a){
// make a copy of Item to get a new instance of Item for the new List
Item newItem = new Item(oldItem);
if(item==newItem.itemIds()){
while(randomBin==newItem.bins()){
randomBin = r.nextInt(50);
}
newItem.setBin(randomBin);
}
newList.add(newItem);
}
return newList;
}