list overwirite all elements - java

i have list array of type Car , but in for loop i set to it some variable strings
but after finished looping i found the last element of list is overwrite all previous elements
Car testset = new Car();
private void populateRandomCars(List<Car> list, int size,
List<Integer> teachers, List<String> state){
try {
for (int i = 0; i < size; i++)
list.add(testset.add(getRandomColor(teachers.get(i)),
getRandomYear(state.get(i))
));
car class :
private String teachers;
private String state;
public Car add(String teachers,String state) {
this.teachers=teachers;
this.state=state;
return Car.this;
}

If you just want to add Car objects in the list. Your for loop should instantiate a new Car object each time.
Car testset = null;
try {
for (int i = 0; i < size; i++) {
testset = new Car();
list.add(testset.add(getRandomColor(teachers.get(i)), getRandomYear(state.get(i))));
// Additional code goes here.
} catch (Exception ex) {
// Exception handling
}

Firstly, it seems that your question is incomplete.
Secondly, to fix up your code, just add the
Car car = new Car();// testset->car
inside the populateRandomCars method.
Then it will create and add a new Car.

Related

Passing multiple arrays of Java objects to another method

I just started learning java, with some minor prior experience in python and a bit of javascript, but not using classes. I have an issue with this code (just for reference, below that I point out exact issue):
public class Race {
Boolean isThereABrokenTruck = false;
private Car[] cars;
private Motorcycle[] motorcycles;
private Truck[] trucks;
private void createVehicles() {
cars = new Car[10];
motorcycles = new Motorcycle[10];
trucks = new Truck[10];
} // creates 10 cars, 10 trucks and 10 motorcycles.
private void simulateRace() {
Weather.setRaining();
for (Car car : cars) {
for (int i = 0; i < 50; i++) {
car.moveForAnHour();
}
}
for (Motorcycle motorcycle : motorcycles) {
for (int i = 0; i < 50; i++) {
motorcycle.moveForAnHour();
}
}
for (Truck truck : trucks) {
for (int i = 0; i < 50; i++) {
truck.moveForAnHour();
}
}
}
private void printRaceResults() {
for (Car car : cars) {
System.out.println("Name: " + car.name);
System.out.println("\n Distance Travelled: " + car.distanceTraveled);
System.out.println("\n Type:" + car.getClass().getName());
}
for (Motorcycle motorcycle : motorcycles) {
System.out.println("Name: " + motorcycle.name);
System.out.println("\n Distance Travelled: " + motorcycle.distanceTraveled);
System.out.println("\n Type:" + motorcycle.getClass().getName());
}
for (Truck truck : trucks) {
System.out.println("Name: " + truck.name);
System.out.println("\n Distance Travelled: " + truck.distanceTraveled);
System.out.println("\n Type:" + truck.getClass().getName());
}
} // prints each vehicle's name, distance traveled ant type.
protected Boolean isThereABrokenTruck() {
return isThereABrokenTruck;
}
public static void main(String[] args) {
Race race = new Race();
race.createVehicles();
race.simulateRace();
race.printRaceResults();
}
}
This code compiles (classes Car, Motorcycle and Truck are defined in my code as well, but are not relevant to the question), however I get runtime null pointer exception on
for (Car car : cars) { // null pointer exception here
for (int i = 0; i < 50; i++) {
car.moveForAnHour();
}
}
so I guess I am not assigning value to cars properly. I am forced to have separate methods to create those vehicles, operate on them and print the results to console. In python I'd probably just return multiple arrays (or lists) and assign their values to different variables, but how do I do it here in Java?
You initialize your vehicle array:
private void createVehicles() {
cars = new Car[10];
motorcycles = new Motorcycle[10];
trucks = new Truck[10];
}
But your array now contains only null-car, null-trucks...
You need to initialize them as well:
private void createVehicles() {
cars = new Car[10];
for (int i = 0; i < cars.length; i++) {
cars[i] = new Car();
}
motorcycles = new Motorcycle[10];
trucks = new Truck[10];
// Init other vehicles as well
}
initial arrays in constructor
public Race() {
createVehicles();
}
You are creating cars variable to hold 10 instances of Car but not storing any value. Add some values to the array and try.
when you initial an array you fill the array with nulls.
so
Car[] cars = new Car[10];
means you have an array with 10 nulls in it. and you are iterating on it. and you will get NullPointerException here car.moveForAnHour();
in createVehicles() you must fill it with objects.
for example :
private void createVehicles() {
cars = new Car[10];
for(int i = 0; i < cars.length; i++) {
cars[i] = new Car();
}
}

Getting size and comparing attribute value from ArrayList in other class

I am trying to create a method which creates a result for a athlete in a competition. I have an ArrayList with the athletes in another class and now I want this method to be able to find the size of the ArrayList and also compare one int attribute of every Athlete with the input number. This is what I have so far, Im really stuck. So my quetions to you are: How do I get my for loop to see the size of the ArrayList athletes? and what is a proper way to check whether or not the input has a matching athlete in the ArrayList(I want it to print out if there is no match)? Thank you
public class ResultList {
Scanner scanner = new Scanner(System.in);
ArrayList<Result> resultList = new ArrayList<Result>();
public ResultList() {
ArrayList<Athlete> temp = new AthleteList().getArrayList();
}
void addResult() {
int competetionNumber;
System.out.print("What is the athletes competetionnumber?");
competetionNumber = scanner.nextInt();
scanner.nextInt();
for (int i = 0; i < athletes.size(); i++) {
}
}
}
Other class with the Athlete ArrayList:
public class AthleteList {
ArrayList<Athlete> athletes = new ArrayList<Athlete>();
public AthleteList () {
}
public ArrayList<Athlete> getArrayList() {
return athletes;
}
You should create a variable that points to the AthleteList class. Then you can see that in the addResult method you just get the ArrayList from the AthleteList and call size() on it and iterate over the Athletes and check the completionNumber(You didn't post the Athlete class so I'm assuming there is a completionNumber property). I create a matched variable to hold on to the matched Athlete. After the loop I check to see if one matched and print out the result.
Hope this helps.
public class ResultList
{
Scanner scanner = new Scanner(System.in);
ArrayList<Result> resultList = new ArrayList<Result>();
AthleteList athleteList;
public ResultList()
{
athleteList = new AthleteList();
}
void addResult()
{
int competetionNumber;
System.out.print("What is the athletes competetionnumber?");
competetionNumber = scanner.nextInt();
scanner.nextInt();
Athlete matched = null;
List<Athlete> athletes = athleteList.getArrayList();
for(int i = 0; i < athletes.size(); i++)
{
if(athlete.completionNumber == completionNumber)
{
//you found a match!!
matched = athlete;
}
}
if(matched == null)
{
System.out.println("No Match Found for " + completionNumber);
}
else
{
System.out.println("Found match: " + matched.toString());
}
}
}
NOTE:
Not sure you need the AthleteList class. It's just holding an ArrayList. If that's all that class will ever do then I suggest you just using an ArrayList. It will make your code cleaner.

Java add items into class as an Array

I have simply this below class structure and I want to add any item to it.
public class Person implements Serializable {
private String name;
private String mobile;
public Person(String n, String e) { name = n; mobile = e; }
public String getName() { return name; }
public String getMobile() { return mobile; }
#Override
public String toString() { return name; }
}
I want to add any item like with this:
people = new Person[]{
new Person("Hi" , " programmer"),
new Person("Hello", " world")
};
My code is this and I want to add items into that by while() my code is don't correct.
people = new Person[]{};
while (phones.moveToNext())
{
people = new Person("Hi" , " programmer");
people = new Person("Hello", " world")
}
you have error in your source code you are trying to put Object of person into array so it will gives you compilation error
to overcome this problem first take List of Type Person and convert it into array and do your business logic on Array its better to use List instead of Array
List<Person> personlst = new ArrayList<Person>();
while (phones.moveToNext())
{
personlst.add(new Person("Hi" , " programmer"));
personlst.add(new Person("Hello", " world"));
}
Object[]arryPer = personlst.toArray();
Person[]people = new Person[arryPer.length];
for (int j = 0; j < arryPer.length; j++) {
people[j] = (Person) arryPer[j];
}
above code of block give you array of type people
You are not defining the number of elements that you want to push into array. Also you are not even making those elements to an array. You should do something like:
int i =0;
people = new Person[1000];// you need to define how many elements you need here or go for list
while (phones.moveToNext())
{
people[i++] = new Person("Hi" , " programmer");
people[i++] = new Person("Hello", " world")
}
Define first the size of your Person.
Person[] people = new Person[10];
then do your iteration for example.
for(int i = 0; i < 0; i++){
people[i] = new Person("Hi" , " programmer");
}
first put all elements in list then form the array:
List<Person> list = new ArrayList<Person>();
while (phones.moveToNext()) {
list.add(new Person("Hi", " programmer"));
list.add(new Person("Hello", " world"));
}
Person[] persons = new Person[list.size()];
list.toArray(persons);
}
Try Arrays.asList
http://www.tutorialspoint.com/java/util/arrays_aslist.html
Note - it is good only for a small number of elements as arrays generally take contiguous memory.
As people have stated above, list is any day better from space point of view.

What will be the output of the following list code execution in java

I am adding five objects in the list with the help of for loop. I am initializing my object outside the for loop. In the body of for loop i am changing the object setter properties and adding it in the list. The output with this is: It will add five objects but all have the same attributes even after setting the different values for the attribute.
See the following code
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class ASD {
public static void main(String args[]) {
List list = new ArrayList<A>();
System.out.println("Before Insert List is " + list);
A obj = new A();
for (int i = 0; i < 5; i++) {
obj.setA(new Random().nextInt(10));
list.add(obj);
}
System.out.println("After Insert List is " + list);
for (int i = 0; i < 5; i++) {
A prObj = (A) list.get(i);
System.out.println("Values are" + prObj.getA());
}
}
}
class A {
int a;
public int getA() {
return a;
}
public void setA(int a) {
this.a = a;
}
}
If I initialize A's object inside the for loop then it will add five objects and also changes the attribute for the objects. Can anyone explain this behaviour
You have created just one instance and setting it several times inside the for loop.Create a new instance of A inside the for loop, not outside it
for (int i=0;i<5;i++) {
A obj = new A();
obj.setA(new Random().nextInt(10));
list.add(obj);
}
When you are doing this -
A obj = new A();
for (int i=0;i<5;i++) {
obj.setA(new Random().nextInt(10));
list.add(obj);
you are actually adding reference to the same object after changing it's attribute setA.
That way, all of the list elements have reference to the same object (with same value of a).
You need to add new objects if you want to have different values -
for (int i=0;i<5;i++) {
obj = new A(); // new object
obj.setA(new Random().nextInt(10));
list.add(obj);

Return ArrayList from ArrayList method type

I'm making a little card deck program that uses an ArrayList for the deck. One of the limitations set upon me is that the method in which I "deal" the cards must be an Arraylist type. The problem I'm running into is that I don't know how to return just a specific index value from the ArrayList. See below.
public ArrayList deal(int n, boolean up){
Card card0 = new Card();
boolean cardFace = card0.state(up);
return al.get(0); //<-- This doesn't work, Netbeans says that it is a string type
//not an ArrayList type. The only thing it will actually
//allow me to return is:
return.al; // But this doesn't work, I don't need to return the whole list,
// just the first element, but Netbeans calls that a String type, not
// ArrayList
So how can I return the first item of the List and still have it be the correct type? The rest of the code doesn't matter, just the Method type and return statement.
EDIT: As requested
package deckofcards;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;
public class Deck{
ArrayList<String> al = new ArrayList<>();
public void shuffle(){
Collections.shuffle(al);
}
public String displayDeck(){
String returnDeck = "";
for(int i = 0; i < al.size(); i++){
String printDeck = al.get(i);
returnDeck += printDeck;
}
return returnDeck;
}
public ArrayList deal(int n, boolean up){
Card card0 = new Card();
boolean cardFace = card0.state(up);
return al.get(0);
}
public void populate(){
al.add(0, "Ace of Spades");
al.add(1, "Two of Spades");
al.add(2, "Three of Spades");
//yadaa yadaa
If you cannot change the signature and it is mandatory to return an arraylist, then you can create an arraylist with just one element and return it. Something like this:
ArrayList returnList = new ArrayList();
returnList.add(al.get(0));
return returnList;
Does not look great to me :-(
In your specific case, al is an ArrayList<String>. That means al.get(...) returns a String. However, your method is declared as returning an ArrayList, which is not a String. You will either need to change your method return type to String, or you will need to construct a new ArrayList and add your single string to it and return that.
Your declared return type needs to match the object you are returning. So for example:
ArrayList<String> al = ...;
String getSingleItem (int index) {
return al.get(index);
}
ArrayList<String> getSingleItemAsArrayList (int index) {
ArrayList<String> single = new ArrayList<String>();
single.add(al.get(index));
return single;
}
ArrayList<String> getItems () {
return al;
}
By the way, it's generally better to specify the type parameter to ArrayList, e.g. ArrayList<Whatever>, as this can save you a lot of casting things around / unchecked conversions and will give you compile-time checking of types.
Is there a reason that you have to return an ArrayList? Essentially, you are trying to create a method that takes a deck, picks a card, and then returns a deck. You could try and use the subList method someone mentioned above. You could create a new ArrayList containing only the card you want, but that's not very efficient. Or, if your goal is to actually return the whole deck, but with the correct card on top (aka in the first position of the ArrayList), there's lots of info about rearranging values in an ArrayList online.
EDIT: Based on your full code, it looks like the goal is to flip the first card face up. You should do that (not gonna do your homework for you!) and then return the ArrayList that the method took in. IRL, imagine handing someone a deck, they flip the first card face up, then hand the deck back to you.
//ADDING AND deleting employees
//Displaying employee list
public class EployeeDB {
static ArrayList e = new ArrayList<>();
public static boolean addEmployee(Employee e1) {
e.add(e1);
System.out.println("Employee added");
return true;
}
public static boolean deleteEmployee(int ecode) {
int temp = 0;
for (int i = 0; i < e.size(); i++) {
if (e.get(i).getID() == ecode) {
temp = temp + 1;
e.remove(i);
break;
}
}
if (temp == 1)
System.out.println("Emp deleted");
else
System.out.println("Deletion unsuccessful, check ecode again");
return true;
}
public static String showPaySlip(int ecode) {
double salary = 0;
int temp = 0;
for (int i = 0; i < e.size(); i++) {
if (e.get(i).getID() == ecode) {
temp = temp + 1;
salary = e.get(i).getSalary();
break;
}
}
if (temp == 1)
return "Salary is" + salary;
else
return "No employye found with the specified ecode";
}
public static ArrayList<Employee> listAll() {
return e;
}
public static void main(String[] args) {
Employee e1 = new Employee();
e1.setID(20);
e1.setName("sai");
e1.setSalary(150.00);
addEmployee(e1);
Employee e2 = new Employee();
e2.setID(30);
e2.setName("kumar");
e2.setSalary(1500.00);
addEmployee(e2);
deleteEmployee(30);
System.out.println(showPaySlip(30));
for (int i = 0; i < e.size(); i++)
System.out.println(
listAll().get(i).getID() + " " + listAll().get(i).getName() + " " + listAll().get(i).getSalary());
}
}

Categories