Java Generic treeMap with comparator declaration without warning - java

There is any way i can do next with out getting the yellow warning / #SuppressWarnings("unchecked")
Generics objects :
P=product to compare,C = custoumer
public static myComparator<Product<P>> comparator= new myComparator<Product<P>>();
comparator declaration is outside "insertIntoMap" method,
i cant use the Product object inside "insertIntoMap" method .
public static <P,C> TreeMap<P, C> insertIntoMap(LinkedHashSet<P> set,C[] ac){
#SuppressWarnings("unchecked")
TreeMap<P,C> treeMap = new TreeMap<P,C>((Comparator<? super P>) comparator);
int itrIndex=0;
Iterator<P> itr = set.iterator();
while(itr.hasNext()){
treeMap.put(itr.next(), ac[itrIndex]);
itrIndex++;
}
return (TreeMap<P, C>) treeMap;
}
public static class myComparator<E> implements Comparator<Product<? super E>>{
#Override
public int compare(Product<? super E> o1, Product<? super E> o2) {
if(o1.getName().length()>o2.getName().length())
return 1;
else return -1;
}
}
Product Class :
public static class Product<E> implements Comparable<E>{
private E serialNum;
private String name;
Product(E serialNum,String name){
setSerialNum(serialNum);
setName(name);
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result;
result = prime * result + ((serialNum == null) ? 0 : serialNum.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
Product<?> other = (Product<?>) obj;
if (serialNum.equals(other.serialNum))return true;
else return false;
}
public E getSerialNum() {
return serialNum;
}
public void setSerialNum(E serialNum) {
this.serialNum = serialNum;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String toString() {
return serialNum.toString()+": "+name;
}
#Override
public int compareTo(E o) {
if(this.hashCode()>o.hashCode())return 1;
else if(this.hashCode()<o.hashCode()) return -1;
else return -1;
}
}
Thanks !

From the code you posted it seems:
myComparator should not be generic:
public class myComperator implements Comparator<Product<?>> {
#Override
public int compare(Product<?> o1, Product<?> o2) {
if (o1.getName().length() > o2.getName().length())
return 1;
else if (o1.getName().length() < o2.getName().length())
return -1;
else
return -1;
}
}
insertIntoMap should only work for P extending Product. Otherwise you cannot use myComperator (which compares Products):
public static <P extends Product<?>, C> TreeMap<P, C> insertIntoMap(
LinkedHashSet<P> set, C[] ac) {
TreeMap<P, C> treeMap = new TreeMap<P, C>(new myComperator());
int itrIndex = 0;
Iterator<P> itr = set.iterator();
while (itr.hasNext()) {
treeMap.put(itr.next(), ac[itrIndex]);
itrIndex++;
}
return treeMap;
}

Related

Find if an object is already present in a HashMap

I am trying to create a HashMap, that adds objects to a line, if they are not already present in this line. This is how I check it:
if (!waiting.containsKey(p)) {
waiting.put(current, p);
current++;
}
Where p is our object, which is stored with an Integer. However, when I run this code. It will store the same object several times under different integers, how can this be prevented?
thats because you call containsKey with the object and not the key:
parameter must be an Integer key
Integer lKey = 0;
if(!waiting.containsKey(lKey)){
waiting.put(current, p);
current++;
}
if your object has an identifier use this identifier for the map.
if(!waiting.containsKey(p.getId())){
waiting.put(p.getId(), p);
current++;
}
otherwise use containsValue():
if(!waiting.containsValue(p)){
waiting.put(current, p);
current++;
}
but then you have to overwrite the equals method.
If you want to use an object as a key, you can override the equals() and hashCode() methods to return and compare the id of the object.
Driver.java
import java.util.HashMap;
import java.util.Map;
public class Driver {
public static void main(String[] args) {
Map<MyObject, Integer> map = new HashMap<MyObject, Integer>();
map.put(new MyObject(1000L, "One"), 1);
map.put(new MyObject(1001L, "Two"), 2);
map.put(new MyObject(1002L, "Three"), 3);
Long id = 1001L;
System.out.println(contains(map, id)); // true
System.out.println(get(map, id)); // 2
}
public static <T, U> boolean contains(Map<T, U> map, T obj) {
return map.containsKey(obj);
}
public static boolean contains(Map<MyObject, Integer> map, Long id) {
return contains(map, new MyObject(id, ""));
}
public static <T, U> U get(Map<T, U> map, T obj) {
return map.get(obj);
}
public static Integer get(Map<MyObject, Integer> map, Long id) {
return get(map, new MyObject(id, ""));
}
}
MyObject.java
public class MyObject {
private Long id;
private String name;
protected Long getId() {
return id;
}
protected void setId(Long id) {
this.id = id;
}
protected String getName() {
return name;
}
protected void setName(String name) {
this.name = name;
}
public MyObject(Long id, String name) {
this.id = id;
this.name = name;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.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;
MyObject other = (MyObject) obj;
if (id == null) {
if (other.id != null) return false;
} else if (!id.equals(other.id)) return false;
return true;
}
#Override
public String toString() {
return "MyObject { id : " + id + ", name : " + name + "}";
}
}

Class cast Exception while using Comparable interface

When I am trying to execute the below code,the compiler is throwing error at line 13 as "java.lang.ClassCastException". Can someone let me know what's wrong with below code?
package chapter11;
import java.util.*;
public class ComparableExample {
public static void main(String[] args) {
// TODO Auto-generated method stub
Item[] items = new Item[3];
items[0] = new Item(102, "Duct Tape");
items[1] = new Item(103, "Bailing Wire");
items[2] = new Item(104, "Chewing Gum");
Arrays.sort(items);
for (Item i : items) {
System.out.println(i.getNumber() + ":" + i.getDescription());
}
}
}
interface Comparable {
int compareTo(Object o);
}
class Item implements Comparable {
private int number;
private String description;
public Item(int number, String description) {
this.number = number;
this.description = description;
}
public int getNumber() {
return number;
}
public String getDescription() {
return description;
}
public int compareTo(Object o) {
Item i = (Item) o;
if (this.getNumber() < i.getNumber())
return -1;
if (this.getNumber() < i.getNumber())
return 1;
return 0;
}
}
Any help is appreciated,
Thanks!!
Remove your Comparable interface, and use the Comparable interface from the Java api.
And also, maybe you can change
public int compareTo(Object o) {
Item i = (Item) o;
if (this.getNumber() < i.getNumber())
return -1;
if (this.getNumber() < i.getNumber())
return 1;
return 0;
}
into :
public int compareTo(Object o) {
Item i = (Item) o;
if (this.getNumber() < i.getNumber())
return -1;
if (this.getNumber() > i.getNumber())
return 1;
return 0;
}

Using union and intersection method in a HashSet

I am having trouble using my custom set,MySet, using the basic function of union and intersecting. The program compiles without error but just returns an empty set.
Anybody see where the problem is?
public class MySet<E> extends TreeSet<E> {
Set<E> set;
public MySet(){
set = null;
}
public MySet(Set<E> set){
this.set = set;
}
public void union(Set<E> s){
set.addAll(s);
}
public void intersection(Set<E> s){
set.retainAll(s);
}
}
Main method
public class TestSet {
public static void main(String[] args) throws FileNotFoundException{
File f1 = new File("courseList1.txt");
File f2 = new File("courseList2.txt");
Scanner scan1 = new Scanner(f1);
Scanner scan2 = new Scanner(f2);
Set<Coarse> set1 = new HashSet<Coarse>();
Set<Coarse> set2 = new HashSet<Coarse>();
MySet<Coarse> mySet = new MySet<Coarse>(set1);
String designator;
int number;
while(scan1.hasNext()){
designator = scan1.next();
number = scan1.nextInt();
set1.add(new Coarse(designator, number));
}
while(scan2.hasNext()){
designator = scan2.next();
number = scan2.nextInt();
set2.add(new Coarse(designator, number));
}
mySet.union(set2);
mySet.intersection(set2);
}
}
It seems that you are trying to implement composition and at the same time extending the tree set, but that is not a good practice, you either use composition and implement the Set interface (backend with a TreeSet) or extends the tree set
Extending the TreeSet
class MySet<E> extends TreeSet<E> {
public void union(Set<E> s){
addAll(s);
}
public void intersection(Set<E> s){
retainAll(s);
}
}
using composition
class MySet<E> implements Set<E> {
private TreeSet<E> set;
public MySet(TreeSet<E> set) {
this.set = new TreeSet<>(set);
}
public void union(Set<E> s){
set.addAll(s);
}
public void intersection(Set<E> s){
set.retainAll(s);
}
#Override
public int size() {
return set.size();
}
#Override
public boolean isEmpty() {
return set.isEmpty();
}
#Override
public boolean contains(Object o) {
return set.contains(o);
}
#Override
public Iterator<E> iterator() {
return set.iterator();
}
#Override
public Object[] toArray() {
return set.toArray();
}
#Override
public <T> T[] toArray(T[] a) {
return set.toArray(a);
}
#Override
public boolean add(E e) {
return set.add(e);
}
#Override
public boolean remove(Object o) {
return set.remove(o);
}
#Override
public boolean containsAll(Collection<?> c) {
return set.containsAll(c);
}
#Override
public boolean addAll(Collection<? extends E> c) {
return set.addAll(c);
}
#Override
public boolean retainAll(Collection<?> c) {
return set.retainAll(c);
}
#Override
public boolean removeAll(Collection<?> c) {
return set.removeAll(c);
}
#Override
public void clear() {
set.clear();
}
#Override
public boolean equals(Object o) {
return set.equals(o);
}
#Override
public int hashCode() {
return set.hashCode();
}
}

Bound Mismatch error when trying to implement comparable interface on generic class

I'm making a custom PriorityQueue class for a homework assignment, and I've run into a roadblock. I can't figure out how to fix this Bound Mismatch error I get in Eclipse; It won't let me try to compile as it says:
Bound mismatch: The type K is not a valid substitute for the bounded parameter <K extends Comparable<K>> of the type Entry<K,V>
PriorityQueue.java:
public class PriorityQueue<K,V> {
private Entry<K,V> _head;
private Entry<K,V> _tail;
private int _size;
public PriorityQueue() {
this._head = null;
this._tail = null;
this._size = 0;
}
public int size() {
return _size;
}
public boolean isEmpty() {
return (size() == 0);
}
public Entry<K,V> min() {
if (_head == null) {
return null;
}
Entry<K,V> current = _head;
Entry<K,V> min = _head;;
while (current != null) {
if (current.compareTo(min) < 0) {
min = current;
}
current = current.getNext();
}
return min;
}
public Entry<K,V> insert(K k, V x) {
Entry<K,V> temp = new Entry<K,V>(k,x);
if (_tail == null) {
_tail = temp;
_head = temp;
}
else {
_tail.setNext(temp);
temp.setPrev(_tail);
_tail = temp;
}
return temp;
}
public Entry<K,V> removeMin() {
Entry<K,V> smallest = min();
smallest.getPrev().setNext(smallest.getNext());
smallest.getNext().setPrev(smallest.getPrev());
return smallest;
}
public String toString() {
return null;
}
public static void main(String[] args) {
PriorityQueue<Integer, Integer> pq =
new PriorityQueue<Integer, Integer>();
pq.insert(4, 2);
pq.insert(5, 1);
pq.insert(1, 5);
System.out.println(pq.min().toString());
}
}
Entry.java:
public class Entry<K extends Comparable<K>,V> implements Comparable<Entry<K,V>> {
private V _value;
private K _key;
private Entry<K,V> _prev;
private Entry<K,V> _next;
public Entry(K key, V value) {
this._value = value;
this._key = key;
this._prev = null;
this._next = null;
}
public V getValue() {
return this._value;
}
public K getKey() {
return this._key;
}
public Entry<K,V> getNext() {
return _next;
}
public void setNext(Entry<K,V> link) {
this._next = link;
}
public Entry<K,V> getPrev() {
return _prev;
}
public void setPrev(Entry<K,V> link) {
this._prev = link;
}
public String toString() {
return "" + this.getValue();
}
#Override
public int compareTo(Entry<K,V> o) {
if (o instanceof Entry<?,?>) {
return this.getKey().compareTo(o.getKey());
}
throw new IllegalArgumentException("Objects are not comparable.");
}
}
You have to make K extends Comparable too for PriorityQueue:
public class PriorityQueue<K extends Comparable<K>,V> {
Indeed, the generic type K will be used for Entry<K,V>, and Entry has the constraint that it must extends (actually implements) Comparable<K>. You have to tell the compiler that the K for PriorityQueue also fulfill this constraint, so it allows you to use Entry<K,V>.
If not, someone could use PriorityQueue with a K that would not extends Comparable, and the compiler would have to check all the use of K to see if there is no constraint that prevents it use.

sorting using comparable java

I'm trying to sort an array of records. But I get "not a Record" error. The method getCt() is in a different class, the program compiles and the array is of the record type. I really don't know what is wrong with this code.
HashTable:
public class HashTable {
private Record [] array;
private int size;
private int indexSize=0;
private boolean updated,found;
public HashTable(int m){
array= new Record[m];
size=0;
}
public void getCt() {
Arrays.sort(array);
// return array[0];
}
Record class:
import java.lang.Comparable;
import java.util.*;
public class Record implements Comparable {
private Integer count;
private DNSkey key;
public Record(DNSkey key) {
this.key = key;
count = 1;
}
public void update() {
count++;
}
public DNSkey getKey() {
return key;
}
public Integer getCount() {
return count;
}
public int compareTo(Object obj) {
if (!(obj instanceof Record)) {
throw new ClassCastException("Not a Record");
}
Record check = (Record) obj;
return getCount().compareTo(check.getCount());
}
public String toString() {
return getKey() + " " + getCount();
}
}
one easy way is to use generics :
public class Record implements Comparable<Record> {
...
public int compareTo(Record check){
return getCount().compareTo(check.getCount());
}
My guess would be null items in the array. "null instanceof Class" will return false.
This will throw the Exception:
Record[] array = new Record[] { new Record(...), null };
Arrays.sort(array);
Use generics! And an #Override annotation.

Categories