Creating an Arraylist of Objects
ArrayList<Matrices> list = new ArrayList<Matrices>();
list.add( new Matrices(1,1,10) );
list.add( new Matrices(1,2,20) );
how to make an arrayList of objects from another class?
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());
}
Create an array list of objects from a file
To get a String from the file, you can call Scanner.nextString(): since your scanner object is called sc, that would look like sc.nextString(). To get an int, you can caller Scanner.nextInt(), and to get a double, you can call Scanner.nextDouble().
You do not want to store these in intermediate values, but instead want to create a student value right away. You can put whatever you want in your Student constructor, as long as the first thing you put evaluates to a String, the second evaluates to an int, and the third evaluates to a double. Since your file always has a String then an int then a double, I think you can use the methods I listed above, and make a call to the Student constructor, to get a Student value.
How to declare an ArrayList of objects inside a class in java?
Have a constructor in your System
class and then
class System {
List<Product> list = new ArrayList<Product>();
public class System() {
list.add(new Product(0, "Coca-Cola", 3.00));
list.add(new Product(1, "Mountain Dew", 2.00));
list.add(new Product(2, "Mango Smoothie", 4.50));
list.add(new Product(3,"Orange Juice", 5.00));
list.add(new Product(4, "Dr. Pepper", 4.50));
list.add(new Product(5, "Sandwich", 3.00));
list.add(new Product(6, "Hamburger", 3.50));
list.add(new Product(7, "Light Sandwich", 4.00));
}
}
Or,
You can
class System {
List<Product> list = new ArrayList<Product>(){
{
add(new Product(0, "Coca-Cola", 3.00));
add(new Product(1, "Mountain Dew", 2.00));
add(new Product(2, "Mango Smoothie", 4.50));
add(new Product(3,"Orange Juice", 5.00));
add(new Product(4, "Dr. Pepper", 4.50));
add(new Product(5, "Sandwich", 3.00));
add(new Product(6, "Hamburger", 3.50));
add(new Product(7, "Light Sandwich", 4.00));
}
};
}
But this is not a good way of writing this, You should not hard code the values in your code like this,
And you can not do
System.out.println(list[0].getName); //Prints "Coca-Cola"
because list is a List,
You can do
System.out.println(list.get(0).getName()); //Prints "Coca-Cola"
Creating an ArrayList from superclass but containing objects from extended classes
Wildcards are here to help you. One can add any class that extends Contact
class to a list which accepts ? super Contact
List<? super Contact> list= new ArrayList<>();
list.add(new EmailContact());
list.add(new PhoneContact());
Creating ArrayList of objects containing ArrayLists as parameters - my code does not seem to create individual ArrayLists?
Your code is incomplete, and the problem is in the code you're not showing: You're passing the same lists to all constructor calls, so all Locations objects are using the same lists for their fields.
This can be fixed by initializing Locations fields at their declarations, eg:
private List<Integer> location_characters = new ArrayList<>();
// repeat this pattern for all List fields
and not passing them lists through the constructor.
If you need to add to the list:
locationsInstance.getlocation_characters().add(foo);
Converting ArrayList of Objects to an ArrayList of Parent Objects
Given a list of Card2:
ArrayList<Card2> card2s;
Do this:
ArrayList<Card> cards = new ArrayList<>(card2s);
The constructor accepts a Collection<? extends Card>
, which in English is a Collection of anything that is or extends Card
.
How to add an object to an ArrayList in Java
You need to use the new
operator when creating the object
Contacts.add(new Data(name, address, contact)); // Creating a new object and adding it to list - single step
or else
Data objt = new Data(name, address, contact); // Creating a new object
Contacts.add(objt); // Adding it to the list
and your constructor shouldn't contain void
. Else it becomes a method in your class.
public Data(String n, String a, String c) { // Constructor has the same name as the class and no return type as such
Accessing specific elements in Arraylist of Objects
You can chain methods together like this.
for(int i = 0; i < users.size(); i++){
if(idNum == users.get(i).getIdNum()){
final Student temp = users.get(i);
System.out.println("Student with an ID of " + temp.getIdNum() + " has an age of " + temp.getAge());
}
}
Here, I chained users.get(i)
to get the Student
at index i
, then I call getIdNum()
, which fetches the ID from that Student
that I just fetched.
Then, I perform a ==
comparison --> Is the ID that the user entered the same as the ID from this particular Student
I am looking at?
If the result is true, then I call users.get(i)
again, which fetches that same Student
again, and then I store that into a temporary Student
variable called temp
. temp
is now referencing that Student
on the ArrayList
that passed the ID check.
Then, I take temp
, and use the getIdNum()
and getAge()
methods that it has (because temp
is an instance of Student
, and Student
has those methods), and use them to create a message that I print onto the command line.
Here is a complete, runnable example.
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Scanner;
public class SOQ_20220514
{
public static class Student {
private String lName;
private int idNumber;
private int age;
public Student() {
lName = "";
idNumber = 0;
age = 0;
}
public Student(String l, int i, int a) {
lName = l;
idNumber = i;
age = a;
}
public void setName(String last) {
lName = last;
}
public String getName() {
return lName;
}
public void setIdNum(int num) {
idNumber = num;
}
public int getIdNum() {
return idNumber;
}
public void setAge(int a) {
age = a;
}
public int getAge() {
return age;
}
}
public static void main(String[] args) throws IOException {
String file = "studentData.txt";
Scanner reader = new Scanner(file);
ArrayList<Student> users = readFile(file);
Student s = new Student();
users.add(s);
Scanner input = new Scanner(System.in);
//user enters idNumber to display age
System.out.println("Enter ID Number"); //exception handling to be added
int idNum = input.nextInt();
//this part is where I'm stuck
for(int i = 0; i < users.size(); i++){
if(idNum == users.get(i).getIdNum()){
final Student temp = users.get(i);
System.out.println("Student with an ID of " + temp.getIdNum() + " has an age of " + temp.getAge());
}
}
}
//METHOD FOR READING FILE
public static ArrayList<Student> readFile(String file)throws IOException{
Scanner reader = new Scanner(new File(file));
ArrayList<Student> list = new ArrayList<Student>();//creates ArrayList with student object
reader.nextLine();//skips first line
while(reader.hasNext()){//splits all text in the file into words
String lName = reader.next();
int idNum = reader.nextInt();
int age = reader.nextInt();
Student users = new Student(lName ,idNum, age);
list.add(users);
}
return list;
}//end method
}
Related Topics
Java Apns Certificate Error with "Derinputstream.Getlength(): Lengthtag=109, Too Big."
How to Install Rjava in R 3.0 in Ubuntu 13.04
Can't Install Rjava on Ubuntu System
Rselenium Unknownerror - Java.Lang.Illegalstateexception with Google Chrome
Unable to Compile Jni Program Rjava
How to Run an R Program from Java
Install Xlsx and Rjava on MACos Mavericks 10.9.5
Simple Program to Call R from Java Using Eclipse and Rserve
Java Object Analogue to R Data.Frame
Version Control for One-Man Project Using Eclipse
How Does One Configure Rjava on Osx to Select the Right Jvm -- .Jinit() Failing
Libjvm.So: Cannot Open Shared Object File: No Such File or Directory