I couldn't remove object.How can I remove a object from an arraylist?
my code
List<kisi> x=new ArrayList<kisi>();
x.add(new kisi("1","betül"));
x.add(new kisi("2","hatice"));
x.add(new kisi("3","selma"));
kisi k=new kisi("2","hatice");
for (int i = 0; i < x.size(); i++) {
if (x.get(i).id==k.id) {
Object obj = x.remove(i);
break;
}
}
my constructor
public class kisi {
public static String id="0";
public static String ad="0";
public kisi(String id,String ad) {
// TODO Auto-generated constructor stub
this.id=id;
this.ad=ad;
}
Solution
Remove the statics from your member variables in your kisi class.
But also note
new kisi("1","betül")
So your id is a String.
When you go through the list comparing ids you do so with ==.
== in java is a same comparison, not an equal comparison. This is unlike the behavior for strings in C# say.
So what you should do is this:
for (int i = 0; i < x.size(); i++) {
if (x.get(i).id.equals(k.id)) { //change here
Object obj = x.remove(i);
break;
}
}
In this simple example this is not causing the problem because the two "2" strings are the same. Which leads me to conclude there's something funny going on your kisi constructor. This is the one I used and the code worked as was:
public class kisi {
public String id;
public kisi(String id, String string2) {
this.id = id;
}
}
A constructor like this will break the code without the .equals call:
public kisi(String id, String string2) {
this.id = id + string2;
}
To remove an Element safely from a list while traversing it you need to do it with an iterator. Otherwise you might get strange results!
Calling remove in foreach loop in Java
In java the only method for removing an item from a list while traversing it is via Iterator.
Related
package generics;
import java.util.ArrayList;
import java.util.List;
public class Generics {
private static List <Box> newlist = new ArrayList<>();
public static void main(String[] args) {
newlist.add(new Box("charlie",30));
newlist.add(new Box("max",29));
newlist.add(new Box("john",22));
// Testing method find -- Start
find ("max",29);
//Testing method find2 -- Start
Box <String,Integer> search = new Box("max",29);
find2(search);
}
public static void find (String parameter, Integer parameter1){
for (Box e : newlist){
if(e.getName() != null && e.getMoney() !=null
&& e.getName().equals(parameter)
&& e.getMoney().equals(parameter1)){
System.out.println("found on position " + newlist.indexOf(e));
break;
}
}
}
public static void find2 (Box e){
for (Box a : newlist){
if (a.equals(e)){
System.out.println("Found");
}else {
System.out.println("Not found");
}
}
}
}
public class Box<T , D>{
private T name;
private D money;
public Box(T name, D money) {
this.name = name;
this.money = money;
}
public T getName() {
return name;
}
public D getMoney() {
return money;
}
#Override
public String toString() {
return name + " " + money;
}
}
Can someone show me how to search for an object in ArrayList.
Method find() it works perfect but in my opinion is wrong and
the reason why I am thinking like that, because I am passing as parameter a string and an integer but should be an box object or maybe I wrong?
In my second method find2() I am trying to pass as parameter an object of Box and when I am trying to search for it I got a false result =(
I am noobie I am trying to understand and to learn.
Stop using raw types!
Box is generic, so if you are not targeting older Java versions, always add generic parameters!.
The declaration of find2 should be like this:
public static void find2 (Box<String, Integer> e)
And you should check whether two boxes are equal in exactly the way you did in find. equals will not work because you did not define an equals method in Box. So:
for (Box<String, Integer> a : newlist){
if (a.getName().equals(e.getName()) &&
a.getMoney().equals(e.getMoney())){
System.out.println("Found");
}else {
System.out.println("Not found");
}
}
You should override Object.equals() on the Box class.
Try to handle null correctly too. Because 2 Box with null names and/or null money are in fact equal.
(you DON'T need to override Object.hashCode() for this, but it's a good practice to do so, just in case it is used in a hashmap or hashset or such).
The easiest way to search and find something in an arraylist is to use the .equals method combined with a for loop to iterate through your lists.
for(int i = 0; i < newList; ++i)
{
if(newlist.equals(Stringname))
{
//it matches so do something in here
}
}
what it is doing here is moving through the list 1 by 1 until it finds something that matches what you entered -> stringName
I used following method to add my data to ArrayList.
ArrayList<Word> wordList = new ArrayList<Word>();
Word word = new Word();
word.set_id(id);
word.setWord(word);
word.setDefinition(definition);
wordList.add(word);
After the add some data, I want find the position of the any id which I want find in ArrayList.
Already I have tried following method to get position by id. But it isn't work.
int position = wordList.indexOf(id);
and
int position = wordList.lastIndexOf(id);
Both codes always generated "position = -1" as a result. How can I do that?
Edited
This is the code of the Word.java class. How can I implement equal method?
public class Word {
private String _id, word, definition, favourite, usage;
public String get_id() {
return _id;
}
public void set_id(String _id) {
this._id = _id;
}
public String getWord() {
return word;
}
public void setWord(String word) {
this.word = word;
}
public String getDefinition() {
return definition;
}
public void setDefinition(String definition) {
this.definition = definition;
}
public String getFavourite() {
return favourite;
}
public void setFavourite(String favourite) {
this.favourite = favourite;
}
public String getUsage() {
return usage;
}
public void setUsage(String usage) {
this.usage = usage;
}
}
indexOf is trying to compare Word objects. Your list doesn't contain ids as the elements, so you get -1.
You need to use a loop and search the list.
int id = 3;
int position = -1;
for (int i = 0; i < wordlist.size(); i++) {
if (wordlist.get(i).getId() == id) {
position = i;
// break; // uncomment to get the first instance
}
}
Note: this will search the whole list to find the last index of that id. So if there are duplicates and you only want the first one (or stop the loop as soon as you find what you want) add a break in the if statement.
Implement equals method in the "Word" object. Inside equals method you can apply equals only to id field.
Create a new Word object with that id and pass that object in indexOf. Don't pass the id in the indexOf. Pass the new of existing Word object with the required id.
Then indexOf will return the valid index of this word object.
For searching the object in a list. you need to override equals method in your Word class. otherwise you will get -1. because indexOf internally used equals method to search the element in list.
The class inside your list should implement hascode() and equals() in order to have indexOf() that works.
Basically, I have 2 classes. One of them has a private member ArrayList(Objects from the other class) and every object from the list has a private field points. I have a method to iterate through the list and get the sum of all points. So I just want to compare list1 > list2 by their summed points. But I'm failing to achieve that - my compareTo() returns always 0.
Here is a short code example of this.
public class StudentsGroup implements IFile, Comparable {
private List<Student> studentsList = new ArrayList<Student>();
public int compareTo(Object o) {
if(StudentsGroup.getTotalPoints(studentsList) < ((StudentsGroup)o).getTotalPoints(studentsList))
return 1;
else if(StudentsGroup.getTotalPoints(studentsList) > ((StudentsGroup)o).getTotalPoints(studentsList))
return -1;
else
return 0;
}
public static int getTotalPoints(List<Student> studentsList1) {
int totalPoints = 0;
for(Student o : studentsList1) {
totalPoints += o.getStudentPoints();
}
return totalPoints;
}
}
The method
if(
StudentsGroup.getTotalPoints(studentsList) <
((StudentsGroup)o).getTotalPoints(studentsList))
You are passing the same studentsList to both sides of the calculation.
The "other group" o is not used at all.
It may look like o is used, but getTotalPoints is a static method and it does not matter what instance you call it on. The compiler will give you a warning about this, too. Do not ignore compiler warnings.
Immediate fix would be to change the code to
if( getTotalPoints(studentsList) < getTotalPoints((StudentsGroup)o).studentsList)
But you should probably change that getTotalPoints method from public static to public (not-static). Instead of the list being passed as a parameter, it can then just use this.studentsList internally.
if (this.getTotalPoints() < ((StudentsGroup)o).getTotalPoints())
In that case I would check the values are not both the same (or both 0)
public class StudentsGroup implements IFile, Comparable<StudentsGroup> {
private List<Student> studentsList = new ArrayList<Student>();
public int compareTo(StudentsGroup sg) {
return Integer.compare(getTotalPoints(), sg.getTotalPoints());
}
public int getTotalPoints() {
return Math.toIntExact(studentsList.stream()
.mapToInt(Student::getStudentPoints).sum());
}
}
By simplifying the code you are less likely to mix up a static method with an instance method (StudentsGroup)o).getTotalPoints(studentsList) just calls StudentsGroup.getTotalPoints(studentsList) as you don't have an instance method.
Eclipse says
This method (findClientByPetsName) must return a result of type Client.
I don't understand why and what to do.
public class Client{
private final String name;
private final Pet pet;
public Client(String name, Pet pet){
this.name = name;
this.pet = pet;
}
public String getName(){
return this.name;
}
public Pet getPet(){
return this.pet;
}
}
public class Clinic {
/**
* This class describes Clinic
*/
private final Client[] clients;
public Clinic(final int size){
this.clients = new Client[size];
}
public Client findClientByPetsName (final String petsName){
for(int i=0; i<clients.length; i++) {
if (clients[i].getPet().getName() == petsName)
return clients[i];
}
}
}
Well, your method must always return something (whose type is Client), even if the for loop is never executed or the if statement is always false (which it will be, since you are not comparing Strings properly - use equals instead of ==).
A possible solution :
public Client findClientByPetsName (final String petsName){
for(int i=0; i<clients.length; i++){
if (clients[i].getPet().getName().equals(petsName))
return clients[i];
}
return null;
}
You need to return a value also if you don't enter in the if statement.
public Client findClientByPetsName (final String petsName) {
for (int i = 0; i < clients.length; i++) {
if (clients[i].getPet().getName().equals(petsName)) {
return clients[i];
}
}
return null;
}
Additionally because petsName is a String I replaced the == with .equals. To do that I supposed that the getName method always returns a not null string. Infact the operator == check for that two objects are the same. Instead the method .equals check for the content of the two objects.
Another alternative is to throw an Exception if the data is not retrieved. Without creating a new Exception type it is possible to use NoSuchElementException.
public Client findClientByPetsName (final String petsName) {
for (int i = 0; i < clients.length; i++) {
if (clients[i].getPet().getName().equals(petsName)) {
return clients[i];
}
}
throw new NoSuchElementException("Pet name: " + petsName + " not found");
}
Note: throwing an Exception can be a good practice to remove from the code check like
if (element != null) {
// Do something
}
When a method declared to return a value. you have to return a value in any situation that can derive from your implemented logic.
If you can't find a valid value to return you can return a null. preferably, in this case the best practice will be to return an Optional object ( in that way you can prevent NullPointerException from your code/api consumer).
Having to ask this question because I am a fool and overwrote old work.
Right now what I need to do is loop through a multidimensional array in one class, then loop through an arraylist(thats currently empty) and use an if statement to check whether or not there are duplicates inside that arraylist, if there aren't, then it will add the record to the arraylist, if it is, it will simply make isFound = false
This is the method that will add the records to the arraylist. Right now it only works up to the second loop. this is the main class, called EAC
public void PopulateRecords()
{
ArrayList<String> categories = new ArrayList<String>();
for (int i = 0; i < Data.stats.length; i++)
{ //System.out.println(Data.stats[i][1]);
for (String category : categories)
{
boolean isFound = false;
if (Data.stats[i][1].equals(category))
{
isFound = true;
}
if (!isFound)
{
categories.add(Data.stats[i][0]);
System.out.println(categories);
}
}
}
}
This is the Category class, and the GetCategory here was used within the populaterecords() method somehow, but that's the one stage of this i'm not fully understanding, because there's a bit or two missing from here that's presumably preventing the method from working
public class Category
{
public String categoryname;
public Category categories;
public static void main(String[] args)
{
new Category();
}
public Category()
{
}
public String GetCategory()
{
return categoryname;
}
public void SetCategory()
{
}
}
This is as specific as I can go, I'm by every definition a pure newbie at java, so any help here is much appreciated
You're looping through an empty ArrayList, so the 2nd loop body will execute 0 times.
ArrayList<String> categories = new ArrayList<String>();
for (int i = 0; i < Data.stats.length; i++)
{ //System.out.println(Data.stats[i][1]);
for (String category : categories) // Here categories is empty, so no loop iterations occur