jcombobox setSelectedItem - java

I have a created a combo box with three items. I am trying to set the selected item by index and value.
When I do setSelectedIndex () the code works well.
I am trying to set the selected item by value. So I try creating another object, with same value(variable name d), and do setSelectedItem but it fails. When I try printing out the selectedItem, it doesn't print 'C C'. It prints the previously selected item 'B B'
So how do set selectedItem by value? Do advice.
Thanks so much!
import javax.swing.JComboBox;
public class testt {
public static void main(String[] args) {
obj a = new obj("A A");
obj b = new obj("B B");
obj c = new obj("C C");
obj[] lst = { a, b, c };
JComboBox box = new JComboBox(lst);
box.setSelectedIndex(1);
System.out.println("value is:"+((obj) box.getSelectedItem()).toString());
obj d = new obj("C C");
box.setSelectedItem(d);
System.out.println(value is:"+((((obj) box.getSelectedItem()).toString());
}
}
class obj {
String value;
public obj(String value) {
this.value = value;
}
public String toString() {
return value;
}
}

Equals and Hashcode issue. The below should solve the problem.
class obj {
String value;
public obj(String value) {
this.value = value;
}
public String toString() {
return value;
}
#Override
public int hashCode() {
int hash = 5;
hash = 17 * hash + Objects.hashCode(this.value);
return hash;
}
#Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final obj other = (obj) obj;
if (!Objects.equals(this.value, other.value)) {
return false;
}
return true;
}

Related

Compare a map of doubles

I hava a Map<Integer,Double> as a field. I need to implement equals() for that given class.
How to compare the double values using a tolerance.
public class Foo {
Map<Integer, Double> data;
public Map<Integer, Double> getData() {
return data;
}
public void setData(Map<Integer, Double> data) {
this.data = data;
}
#Override
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof Foo))
return false;
Foo foo = (Foo) o;
if (this.data.size() != foo.getData().size())
return false;
Set<Integer> keySet1 = data.keySet();
Set<Integer> keySet2 = foo.getData().keySet();
// keys should same
if (keySet1.containsAll(keySet2) && keySet2.containsAll(keySet1)) {
// for the same key, the values are close
for (Integer key : keySet1) {
if (!isEntryEqual(data.get(key), foo.getData().get(key))) {
return false;
}
}
return true;
}
return false;
}
// also need to override the hashCode method
#Override
public int hashCode() {
List<Integer> keys = new ArrayList<Integer>(this.data.keySet());
return Objects.hash(keys);
}
public static final Double PRECISION = 0.0001;
private static boolean isEntryEqual(Double d1, Double d2) {
return d1 - d2 < PRECISION;
}
}

how can i print custom class Duplicate if i am adding that object in list?

How can i print the duplicate of custom class object if i am adding that object inside list.
class Bank{
int id;
String name;
public Bank(int id,String name){
this.id=id;
this.name=name;
}
#Override
public boolean equals(Object obj) {
// TODO Auto-generated method stub
return super.equals(obj);
}
#Override
public String toString() {
return id+"\t"+name;
}
}
public class Service {
public static void main(String[] args) {
List<Bank> al=new ArrayList<Bank>();
Bank a=new Bank(11,"employee");
Bank b=new Bank(11,"employee");
Bank c=new Bank(12,"Bank");
Bank d=new Bank(12,"Bank");
al.add(a);
al.add(b);
al.add(c);
al.add(d);
}}
Here four bank object i am adding inside list. But a,b pointing to same object and similarly c and d pointing to same object How can i pointing to duplicate from above List.
You have 2 options to achieve this...
1st one is out of the box:
you need to use a Set, this collection doesnt allow duplicates, but you has no insertion order
2nd option.
you can write a method that is checking in the list is the element you are trying to insert is already there... list.contains(bank); where bank is the mthod to check...
in both cases is necessary to override the methods hashcode and equals(you already have this) in the class bank.
Example:
static List<Bank> al;
public static void main(String[] args) {
al = new ArrayList<Bank>();
Bank a = new Bank(11, "employee");
Bank b = new Bank(11, "employee");
Bank c = new Bank(12, "Bank");
Bank d = new Bank(12, "Bank");
addIfNotinList(a);
addIfNotinList(b);
addIfNotinList(c);
addIfNotinList(d);
System.out.println(al);
}
private static void addIfNotinList(Bank bank) {
if (!al.contains(bank)) {
al.add(bank);
}
}
and the Bank class
public class Bank {
int id;
String name;
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + id;
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Bank other = (Bank) obj;
if (id != other.id)
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
public Bank(int id, String name) {
this.id = id;
this.name = name;
}
#Override
public String toString() {
return "Bank [id=" + id + ", name=" + name + "]";
}
}
Implement equals according to:
public boolean equals( Object obj ){
if ( this == obj ) return true;
if ( !(obj instanceof Bank) ) return false;
Bank other = (Bank)obj;
return this.id == other.id && this.name == other.name;
}
Perhaps comparing the id alone would be sufficient to establish equality.
Now you can do:
List<Bank> al=new ArrayList<Bank>();
Bank a=new Bank(11,"employee");
al.add( a );
Bank b=new Bank(11,"employee");
if( al.contains( b ) ){
// duplicate
} else {
al.add( b );
}

Check ArrayList for duplicates

Class:
public class Variant
{
private String variant;
private String quantity;
//getters and setters
}
ArrayList:
ArrayList<Variant> variantList = getVariantsList();
Now I want to check whether variantList contains a duplicate entry of variant or not? Please note that variant having two entries with different quantity are to be considered as duplicates.
You can simply ovveride your equals method in your Variant class and provide all the rules for equality in that method.
#Override
public boolean equals(Object obj) {
..
Then you can use contains method or just pass it to a Set, that eliminates all your duplicates.
If you want variant having two entries with different quantity also considered as dup, then you can add that condition in your equals.
Override equals(Object obj) method and try to compare the object on variant and quantity.
Try to loop thru the variantList and do check for duplicity using variantList.contains(variant).
There are two things you need to do:
Override the equals() in your Variant class(minimal code below):
Please note that the below code only checks for quantity and not the variant prop. Your IDE might help you to generate the equals() as well.
#Override
public boolean equals(Object object) {
boolean isEqual = (this == object);
if(object instanceof Variant){
Variant variant = (Variant) object;
isEqual = this.quantity.equals(variant.quantity);
}else{
isEqual = false;
}
return isEqual;
}
Check if the List contains the object - which will use the equals() to check if both are equal.
for (Variant variant : variantList) {
if (variantList.contains(variant)) {
//do logic if its present
}
}
Just check one object with other objects of list
Override equals method in Variant class
#Override
public boolean equals(Object obj) {
if (obj != null) {
if (obj instanceof Variant) {
Variant temp = (Variant) obj;
return this.quantity.equals(temp.quantity); //for different quantity
} else {
return false;
}
}
return false;
}
Then check :
for (int i = 0; i < variantList.size(); i++) {
for (int j = 0; j < variantList.size(); j++) {
if (i != j) {
if (iList.get(i).equals(iList.get(j))) {
//logic when duplicate
break;
}
}
}
}
Follow the below guidelines:
Your Class Variant must override the equals method, since you define a duplicate condition based on quality hence in the equals method check for quality attribute value i.e.
public class Variant {
private String variant;
private String quantity;
public Variant(String variant, String quantity) {
this.variant = variant;
this.quantity = quantity;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result
+ ((quantity == null) ? 0 : quantity.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Variant other = (Variant) obj;
if (quantity == null) {
if (other.quantity != null)
return false;
} else if (!quantity.equals(other.quantity))
return false;
return true;
}
}
Create a method which basically checking whether your list contains the duplicate entries(Variant) or not and return true and false accordingly:
private static boolean isListContainsDuplicateEntries(
ArrayList variantList) {
final List setToReturn = new ArrayList();
for (Variant v : variantList) {
if (!setToReturn.contains(v)) {
setToReturn.add(v);
} else {
return true;
}
}
return false;
}
Now, test the functionality:
public static void main(String[] args) {
Variant variant1 = new Variant("1", "100");
Variant variant2 = new Variant("2", "200");
Variant variant3 = new Variant("3", "200");
ArrayList<Variant> variantList = new ArrayList<>();
variantList.add(variant1);
variantList.add(variant2);
variantList.add(variant3);
System.out.println(Variant.isListContainsDuplicateEntries(variantList));
Output: true
You can use contains():
if (variantList.contains(**<some other Variant object>**)){
...
}
You can simply override your equals method in your Variant and try like this
List<Varient> list =getVariantsList();
System.out.println("here list size"+list.size());
Set<Varient> set = new HashSet<Varient>(list);
System.out.println("here"+set.size());
Create a varient Object:
public class Varient {
private String variant;
private String quantity;
public String getVariant() {
return variant;
}
public void setVariant(String variant) {
this.variant = variant;
}
public String getQuantity() {
return quantity;
}
public void setQuantity(String quantity) {
this.quantity = quantity;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Varient)) return false;
Varient varient = (Varient) o;
if (!quantity.equals(varient.quantity)) return false;
if (!variant.equals(varient.variant)) return false;
return true;
}
#Override
public int hashCode() {
int result = variant.hashCode();
result = 31 * result + quantity.hashCode();
return result;
}
}
Here is your main Program;
public class Test {
public static void main (String [] args){
// getVariantsList() here your list
List<Varient> list =getVariantsList();
Set<Varient> set = new LinkedHashSet<Varient>(list);
}
}
public class Variant {
private String variant;
private String quantity;
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((variant == null) ? 0 : variant.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Variant other = (Variant) obj;
if (variant == null) {
if (other.variant != null)
return false;
} else if (!variant.equals(other.variant))
return false;
return true;
}
public String getVariant() {
return variant;
}
public void setVariant(String variant) {
this.variant = variant;
}
public String getQuantity() {
return quantity;
}
public void setQuantity(String quantity) {
this.quantity = quantity;
}
public static void main(String[] args) {
// HashSet<Variant> set = new HashSet<>();
// LinkedHashSet<Variant> linkedSet = new LinkedHashSet<>(); // stores
// in input order
/*
* You can use treeset to store data in custom order, in this case
* lexicographically
*/
TreeSet<Variant> treeSet = new TreeSet<>(new VariantComparator());
}
}

Java: HashSet multiple types

I have a program that I have to use a HashSet for. My question arises from the fact that HashSets mainly contain one object, but if I wish to send information to the other class, it takes three objects: one string, one int, and one boolean.
The assignment says that I must use a HashSet
Constructor I am trying to send information to:
public Magic (String name, int size, boolean isVisible)
I have a class that is supposed to be sending sets of spells containing name, size, and isVisible.
Magic.go() class:
public void go()
{
int i = 0;
while (i < size) {
if (isVisible == true) {
System.out.println(name + "!");
}
i++;
}
}
Just create an object which contains all the three fields like this:
import java.util.Objects;
public class NameSizeVisible {
private final String name;
private final int size;
private final boolean isVisible;
public NameSizeVisible(String name, int size, boolean isVisible) {
this.name = name;
this.size = size;
this.isVisible = isVisible;
}
public String getName() {
return name;
}
public int getSize() {
return size;
}
public boolean isVisible() {
return isVisible;
}
#Override
public int hashCode() {
return Objects.hash(name,size,isVisible);
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
NameSizeVisible other = (NameSizeVisible) obj;
if (isVisible != other.isVisible)
return false;
if (!Objects.equals(name, other.name))
return false;
if (size != other.size)
return false;
return true;
}
}
You can use a HashSet that stores Objects. So you would have:
HashSet<Object> set = new HashSet<>();
set.add(name);
set.add(size);
set.add(isVisible);
Then when you access the objects you just need to cast them to their respective types:
String name = "";
int size = 0;
boolean isVisible = false;
for (Object o : set) {
if (o instanceof String) {
name = (String) o;
} else if (o instanceof int) {
size = (int) o;
} else {
isVisible = (boolean) o;
}
}

Java - get an Integer value from String or int - avoiding instanceof

Is there a single line implementation for the getInt method?
If not - can one implement it without using instanceof?
public class ParseInt {
public static void main(String[] args) {
Object intArr[] = { "131", 232, new Integer(333) };
for (Object intObj : intArr) {
System.out.println(getInt(intObj));
}
}
private static int getInt(Object obj) {
return // ???
}
}
Use Integer.valueOf(obj.toString)
private static int getInt(Object obj) {
return Integer.valueOf(obj.toString());
}
This will work for your object array
Try something like...
private static int getInt(Object obj) {
if (obj instanceof String) {
return Integer.parseInt((String) obj);
} else if(obj instanceof Integer){
return (Integer) obj;
} else{
return 0; // or else whatever you want
}
}

Categories

Resources