Removing a selected object from an array [duplicate] - java

This question already has answers here:
Remove specific index from array in java
(6 answers)
Why we need to override hashCode and equals?
(4 answers)
Closed 5 years ago.
I have created an array of objects (object representing a flight),
and i'm trying to create a method to remove a specific object from that array, without changing it's length.
I have written the following method :
public boolean removeFlight (Flight f) {
for (int i = 0 ; i < _noOfFlights ; i++) {
if (_flightsSchedule[i].equals(f)) {
_flightsSchedule[i] = _flightsSchedule[(i+1)];
_noOfFlights--;
return true;
}
}
return false;
}
_noOfFlights represents the number of object currently in the array.
For some reason it returns "false" when given an object that was added to the array.

You need to be careful not to change the ground under your feet. You also don't want to return in the middle of the loop, otherwise you won't have moved all the elements properly.
You could do something like this:
public boolean removeFlight (Flight f) {
boolean found = false;
for (int i = 0 ; i < _flightsSchedule.length; i++) {
if (f.equals(_flightsSchedule[i])) {
found = true;
} else if (found) {
_flightsSchedule[i - 1] = _flightsSchedule[i];
}
}
if (found) {
_noOfFlights--;
_flightsSchedule[_flightsSchedule.length - 1] = null;
}
return found;
}
Also, note that I've set the last element to null to avoid an inadvertent memory leak.

Related

ArrayList looping only outputs the last item [duplicate]

This question already has answers here:
Check if a value exists in ArrayList
(4 answers)
Closed 2 years ago.
I am trying to loop through an ArrayList, and compare each index value to a default value, if the index value matches the default value, I want to return true, the only problem is that, it always returns true only to the index item that is added. Since my class doesn't have a main method, I have added those values during the class constructor initialization.
public class CountryFinderImpl implements CountryFinder{
List<String> Countries = new ArrayList<String>();
public CountryFinderImpl() {
Countries.add("canada");
Countries.add("japan");
Countries.add("usa");
}
#Override
public boolean forWeather(String country) {
// TODO Auto-generated method stub
country = country.toLowerCase();
boolean c=false;
for(int i=0; i<Countries.size();i++) {
if(Countries.get(i).equals(country)) {
//System.out.println(country+"Weather available");
c=true;
}else {
//System.out.println(country+"weather unavilable");
c=false;
}
}
return c;
}
}
The country parameter is passed from another class, which takes the country value from the user.
In each iteration of the loop, you overwrite c, regardless of its value, so you'll always return the result fot the last element. One solution is to use the "early return" idiom and return true immediatly when the item is found:
#Override
public boolean forWeather(String country) {
country = country.toLowerCase();
for (int i = 0; i < Countries.size() ;i++) {
if (Countries.get(i).equals(country)) {
return true;
}
}
return false;
}
Note, however, that this is just a reimplementation of the contains method, so you might as well just use it:
#Override
public boolean forWeather(String country) {
return Countries.contains(country.toLowerCase());
}

How to fix ConcurrentModificationException when using foreach to iterate over a List? [duplicate]

This question already has answers here:
Java - adding elements to list while iterating over it
(5 answers)
Closed 5 years ago.
am trying to add objects to an arraylist after verifying either that object already exits in the list or not. But am getting a ConcurrentModificationException and I don't know how to fix it.
Any help?
here is the code that throws the exception:
List<ContexteNb> projets = service.findByprojet(p);
List<ProjetVTO> models = new ArrayList<>();
for (ContexteNb contexteNb : projets) {
ProjetVTO model = new ProjetVTO();
model.setNbillets(contexteNb.getNbBillet());
model.setAnnee(contexteNb.getDimDate().getAnnee());
model.setPriorite(contexteNb.getDimPriorite().getPriorite());
if (models.isEmpty()) {
models.add(model);
}
else{
for (ProjetVTO projetModel : models) {
if ((projetModel.getAnnee() == model.getAnnee())
&& (projetModel.getPriorite().equals(model.getPriorite()))) {
projetModel.setNbillets(projetModel.getNbillets() + model.getNbillets());
} else {
models.add(model);
}}}}
thanks,
The exception results from adding an element to the models List while iterating over it.
You have to change your logic. I suspect the logic of your inner loop is wrong anyway, and fixing it will also solve your problem. You probably want to search first if the List contains any element matching model and modify it if found, and only add a new instance to the List if you don't find a match (i.e. after the loop is over).
Your inner loop would look like this:
if (models.isEmpty()) {
models.add(model);
} else {
boolean found = false;
for (ProjetVTO projetModel : models) {
if ((projetModel.getAnnee() == model.getAnnee()) && (projetModel.getPriorite().equals(model.getPriorite()))) {
projetModel.setNbillets(projetModel.getNbillets() + model.getNbillets());
found = true;
break;
}
}
if (!found) {
models.add(model);
}
}
or simply (you can eliminate the outer condition):
boolean found = false;
for (ProjetVTO projetModel : models) {
if ((projetModel.getAnnee() == model.getAnnee()) && (projetModel.getPriorite().equals(model.getPriorite()))) {
projetModel.setNbillets(projetModel.getNbillets() + model.getNbillets());
found = true;
break;
}
}
if (!found) {
models.add(model);
}

Passing method of one class into another [duplicate]

This question already has answers here:
Passing a method from another class
(4 answers)
Closed 5 years ago.
My problem is that I need to getSymbol from Element class.
I would normally establish an object in PeriodicTable like this:
Element e = new Element();
then use e.getSymbol within method in order to use it for comparison.
So, in order to complete first task and print entire list of elements, I declared an array within PeriodicTable like this:
Element[] objects = new Element[ARRAY_SIZE];
I'm guessing I declared it correctly, as it does run entire list of elements.
Again, I am having problems getting getSymbol into my method in PeriodicTable.
Any helpful suggestions, please?
For this method, a user will input a symbol for an element. The method will search for the element and return its index (in the array). Then, it will use the index to display that single element and all of its other information, using the toString method from the Element class.
public int searchBySymbol(String sym)
{
int index = 0;
boolean found = false;
for (int i = 0; i < objects.length; i++)
{
objects[i] = objects.getSymbol;
}
while (index < objects.length && !found)
{
if (objects[index].equals(sym))
{
found = true;
}
else
{
index++;
}
}
if(found)
{
System.out.println("Found at position: " + index);
System.out.println(objects[index].toString());
}
else
{
System.out.println("Not found");
}
}
You definitely don't need two loops in there first of all, there are two solutions to this:
(Recommended) If searching Elements by symbol will be the your main way of looking up Elements, consider using a HashMap to contain the data rather than an Element array as HashMaps allow look up of objects by a key e.g. HashMap<String, Element>. Lookup the HashMap API or check this example: http://beginnersbook.com/2013/12/hashmap-in-java-with-example/
(Quick fix) Rather than using two loops to get the field and compare, in Java it is good practice to define accessor methods such as getSymbol() and return the field rather than directly accessing it. Using this method you can simplify your code into...
for (Element e : objects) {
if (e.getSymbol().equals(sym) {
return true;
}
}
//return false after the loop omits the need for an explicit boolean variable`
Edit: Usual for loop construct for index access. The index number is essentially tracked by the iterator variable int i so you do not need a separate variable to track it.
for (int i = 0; i < objects.length; i++) {
if (objects[i].getSymbol().equals(sym)) {
//print i to show index number
//print objects[i].toString();
return true;
}
}
//print not found...
return false;

fetching data from ArrayList [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 8 years ago.
I have method which returns List of objects, I m facing a problem while fetching a data from list, I m getting null pointer exception when i am trying to fetch the data.
method which returns List:
public List <EstimationResivion> getEstimationRevision(double rev_id){
List<EstimationDetailRevision> estDetail=estDetailRev(rev_id);
List<EstimationPanelRev> estPanelrev=estPanelRev(rev_id);
List<EstimationPannelDetailRevision> estimationpaneldetailrev=estPanelDetailRev(rev_id);
List<EstimationResivion> estRev=estRevision(rev_id);
EstimationResivion ed= new EstimationResivion();
ed.setEstimationdetailRev(estDetail);
ed.setEstimationpanelRev(estPanelrev);
ed.setEstimationpaneldetailRev(estimationpaneldetailrev);
System.out.println("Size before: "+estRev.size());
estRev.add(ed);
return estRev;
}
estDetailRev code:
private List<EstimationDetailRevision> estDetailRev(double d){
return getJdbcTemplate().query("SELECT * FROM estimation_detail_rev WHERE rev_id=?", new Object[] {d }, new EstimationDetailRevRowMapper());
}
estRevision code
private List<EstimationResivion> estRevision(double d){
return getJdbcTemplate().query("SELECT * FROM estimation WHERE est_revision=?", new Object[] {d }, new EstimationRevRowMapper());
}
estRevision will return list of List<EstimationResivion> which i am storing in estRev.
code from where i am calling getEstimationRevision and trying to fetch data from list
public void getRevision(){
double d=0;
List<EstimationResivion> est=estimationdao.getEstimationRevision(d);
for(EstimationResivion er:est){
System.out.println(er.getEstContactPerson());
System.out.println(er.getEstCustomer());
System.out.println(er.getRevId());
// epd=er.getEstimationpaneldetailRev();
List<EstimationDetailRevision> edr=er.getEstimationdetailRev();
for(EstimationDetailRevision estimaitonDetail:edr){
estimaitonDetail.getCompCategory();
estimaitonDetail.getCompMake();
}
}
I am getting null value when i call er.getEstimationdetailRev();
if i specify the index i am able to getdata something like this:
List<EstimationDetailRevision> edr=est.get(64).getEstimationdetailRev();
My question is how can i fetch data without specifying index ?
One of your elements is null (not a value). Let's find out which,
// for(EstimationResivion er:est){
for (int index = 0; index < est.size(); index++) {
EstimationResivion er = est.get(index);
if (er == null) {
System.out.println("element at index " + index + " is null");
continue; // <-- move to the next index
}
// ...
List<EstimationDetailRevision> edr=er.getEstimationdetailRev();
if (edr == null) {
System.out.println("edr at index " + index + " is null");
continue; // <-- move to the next index
}
Also, you could (and should) use a debugger on your code.

two equal array lists but java does not see equal [duplicate]

This question already has answers here:
What's the difference between ".equals" and "=="? [duplicate]
(11 answers)
Closed 8 years ago.
Here I declare two array lists
ArrayList<Location> possibleMoves = new ArrayList<Location>();
possibleMoves.add(new Location(0, 1));
possibleMoves.add(new Location(1, 0));
ArrayList<Location> possibleMoves1 = new ArrayList<Location>();
possibleMoves1.add(new Location(0, 1));
possibleMoves1.add(new Location(1, 0));
its obvious that those 2 array lists are the same, but when I run this check it always seems to fail.
if(possibleMoves == possibleMoves1){
System.out.println("lol");
}
I have also tried this and it failed
assertTrue("Player 1 1st piece could play to the left and down!",
arrayListsEqual(possibleMoves, possibleMoves1));
this is the method of arrayListsEqual
private boolean arrayListsEqual(ArrayList<Location> a, ArrayList<Location> b) {
if (a.size() != b.size()) {
return false;
}
int size = a.size();
boolean thisOneFound = false;
for (int i = 0; i < size; i++) {
thisOneFound = false;
for (int j = 0; j < size; j++) {
if (a.get(i).equals(b.get(j))) {
thisOneFound = true;
break;
}
}
if (!thisOneFound) {
return false;
}
}
return true;
}
2 issues:
The "Location" objects are different instances. so they are totally unrelated objects.
The list themselves are different instances.
first: you need to check equality with the "equals" method of the lists:
list1.equals(list2).
also, you need to make sure you save the SAME object in those lists (by using the same instance) or to implement the "equals" and "hashmap" methods in the "Location" class.
once that is done it should work.
good luck :)
Please read about the difference between == and equals. == checks whether both References refer to the same instance whereas equals tests for equality. Have a look at the answers to this question.
You cannot compare reference objects with == , ArrayList is not a primitive data type.

Categories