I tried searching, but to no avail, I hope you can help me out.
I have an ArrayList
containing objects, which all have 4 integer variables. I want my program to throw an Exception
, if some of the variables for these objects are identical.. I'll try and write in pseudocode:
for(Object x : ArrayList)
{
if(x.Variable == someVariables)// all the variables for the objects in the arraylist
{
throw exception
}
}
This is a newbie question, but I hope you can help me out, thanks.
Inside your for loop add them into a set if add method returns false duplicate exist
for(Object x : ArraList)
{
Set<Integer> set=new HashSet<Integer>();
for(int i:x.getAllValues()){
boolean status=set.add(i)
if(status==false){
//throw exception
}
}
}
write get values method in your object class
OR
Simply create a set from list and check their length
Set<Integer> set= new HashSet<Integer>(list);
if(set.size()!=list.size()){
//contains duplicates
}
Id recommend to implement your value check inside of your class which is your Object
's type. To me it seems to be important that a "thing" like your Object
is able to perform a validity check on it's own values. I give you an example:
public class Container {
// declaration of your four variables
// other code, maybe getters and setters
/**
* Checks if all variables are pairwise inequal
* @return true if so, false otherwise
*/
public boolean isValid() {
// check vars
}
}
This way your routine to check all objects of your list is very easy:
for (Container x : arrayList) {
if (!x.isValid()) {
throw new RuntimeException("A bad thing just happend!");
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.