How to implement the comparable and equals method in this Tree Map,so that my Contains Value return true.
How to do it?
How to implement?
import java.util.*;
class a
{
public static void main(String arr[])
{
TreeMap<String,Emp> map=new TreeMap<String,Emp>();
map.put("HEllo",new Emp("ada",23));
map.put("aehqn",new Emp("rewr",343));
map.put("rffewrf",new Emp("saerfwe",893743));
Set<Map.Entry<String,Emp>> x=map.entrySet();
Iterator<Map.Entry<String,Emp>> itr =x.iterator();
while(itr.hasNext())
{
Map.Entry<String,Emp> m=itr.next();
System.out.println(m.getKey());
Emp e=m.getValue();
e.display();
System.out.println();
}
System.out.println("NOw the value we will finid is"+map.containsValue(new Emp("ada",23)));
}
}
class Emp
{
String n;
int i;
public Emp(String n,int i)
{
this.n=n;
this.i=i;
}
public void display()
{
System.out.println("there are string "+n+" int"+i);
}
}
Thanks in advance
Your Code will look like
class Emp implements Comparable<Emp>
{
String n;
int i;
public Emp(String n,int i)
{
this.n=n;
this.i=i;
}
public void display()
{
System.out.println("there are string "+n+" int"+i);
}
public boolean equals(Object o){
if(o instanceof Emp){
Emp d = (Emp)o;
return ((d.n.equals(n)) && (d.i==i));
}
return false;
}
public int hashCode(){
return i/2 + 17;
}
public int compareTo(Emp d){
if(this.i>d.i)
return 1;
else if(this.i<d.i)
return -1;
return this.n.compareTo(d.n);
}
}
Please Ignore if any syntax error and you can improve method implementations also.
The containsValue() method of the Map interface uses the equals() method of the Object class.so in your case you have to override the equals() method and when you override the equals() method it is advised to override the hashCode() method too.
Below is the correct code:-
public class a
{
public static void main(String arr[])
{
TreeMap<String,Emp> map=new TreeMap<String,Emp>();
map.put("HEllo",new Emp("ada",23));
map.put("aehqn",new Emp("rewr",343));
map.put("rffewrf",new Emp("saerfwe",893743));
Set<Map.Entry<String,Emp>> x=map.entrySet();
Iterator<Map.Entry<String,Emp>> itr =x.iterator();
while(itr.hasNext())
{
Map.Entry<String,Emp> m=itr.next();
System.out.println(m.getKey());
Emp e=m.getValue();
e.display();
}
System.out.println("Now the value we will find is"+map.containsValue(new Emp("ada",23)));
}
}
class Emp
{
String n;
int i;
public Emp(String n,int i)
{
this.n=n;
this.i=i;
}
public void display()
{
System.out.println("there are string "+n+" int"+i);
}
#Override
public boolean equals(Object obj) {
if(obj==null)
{
return false;
}
if(this.getClass().equals(obj.getClass()))
return true;
else
return false;
}
#Override
public int hashCode() {
return super.hashCode();
}
}
Related
public class Cars implements Comparable{
private String company, model;
private int price;
public Cars(String company, String model, int price){
this.company=company;
this.model=model;
this.price=price;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + price;
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Cars other = (Cars) obj;
if (price != other.price)
return false;
return true;
}
public String toString(){
return String.format("Comapany: %s, Model: %s, Price: %d", this.company, this.model, this.price);
}
public String getCompany() {
return company;
}
public void setCompany(String company) {
this.company = company;
}
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
public int compareTo(Object obj) {
return this.price-((Cars)obj).price;
}
}
public class BlockingQueueExample {
BlockingQueue<Cars> queue;
Random random=new Random();
private boolean running=false;
public BlockingQueueExample(BlockingQueue<Cars> queue){
this.queue=queue;
running=true;
}
public void producer() throws InterruptedException{
while(running){
int add_car=random.nextInt(5);
Cars value=null;
switch(add_car){
case 0:value=new Cars("BMV", "q7", 4000);break;
case 1:value=new Cars("Renault","KWID", 2000);break;
case 2:value=new Cars("Porche","Cayenee", 3000);break;
case 3:value=new Cars("Skoda", "Rapid", 2500);break;
case 4:value=new Cars("Volkswagen", "Ameo", 3500);break;
}
queue.put(value);
System.out.println("PRODUCER "+ value);
System.out.println();
}
}
public void consumer() throws InterruptedException{
while(running){
Thread.sleep(500);
if(random.nextInt(5)==0){
Cars value=queue.take();
//Collections.sort((List<Cars>) queue);
System.out.println("CONSUMER Taken value: "+value +", Queue size: "+queue.size()+"\n"+queue);
System.out.println();
}
}
}
public void stop(){
running=false;
// method to sort queue
System.out.println("Sorted queue:"+"\n"+queue);
}
}
I tried Arrays.sort(queue.toArray()), Collections.sort(queue), doesn;t wok ; It's for a presentation for tomorrow.... someone pls welp
Obviously sorting an ArrayBlockingQueue wouldn't work, as it would go against its FIFO design. If you want a sorted Queue, then you should utilize a PriorityQueue.
You can't sort the BlockingQueue, but you can sort an array of the elements.
You almost had it right with your Arrays.sort(queue.toArray()) attempt. You just need to remember the array and print it, not the unsorted queue.
Cars[] arr = queue.toArray(new Cars[queue.size()]);
Arrays.sort(arr);
System.out.println("Sorted elements:\n" + Arrays.toString(arr));
Unrelated
You should not use the raw generic Comparable. Change that to Comparable<Cars>.
Also, subtracting integer values to produce compare() value is error prone (numeric overflow). Use Integer.compare() instead.
public class Cars implements Comparable<Cars> {
// lots of code
#Override
public int compareTo(Cars other) {
return Integer.compare(this.price, other.price);
}
}
This is my whole code, the problem requires me to use Array for solution.
import java.lang.reflect.Array;
public class MyStack<T> {
public MyStack (Class<T[]> _class,int size){
final T[] values = (T[]) Array.newInstance(_class,size);
this.values = values;
this.size=size;
}
private T[] values;
private int top=0,size;
public void push(T nextElement){
if(isFull()){
System.out.println("full");
}
else {
values[top++] = nextElement;
}
}
public T pop(){
if(isEmpty()) {
System.out.println("empty");
return null;
}
else {
return values[top--];
}
}
public boolean isEmpty(){
if (top==0)return true;
return false;
}
public boolean isFull(){
if(top==size-1)return true;
else return false;
}
public static void main(String args[]){
MyStack<Integer> myStack = new MyStack<Integer>(Integer[].class,9);
for (int i =0;i<10;i++)
{
myStack.push(i);
}
while(!myStack.isEmpty()){
System.out.println(myStack.pop());
}
}
}
When i compile it it throws Exception in thread "main" java.lang.ArrayStoreException: java.lang.Integer at values[top++] = nextElement; no matter which type i used from String, Integer or any other Objects.
Is there a way to fix this problem ?
You constructor takes a Class<T[]> but should take a Class<T>, also you don't need a variable shadow on values. I'd write it like
public MyStack(Class<T> _class, int size) {
this.values = (T[]) Array.newInstance(_class, size);
this.size = size;
}
You don't need if else chains for isEmpty (just return the condition you are testing directly) - like
public boolean isEmpty() {
return top == 0;
}
Or for isFull
public boolean isFull() {
return top == size - 1;
}
How and why am I getting the compiler error ("class, interface, or enum expected")? Here is the code:
public class RolloverCounter{
private int counter=0;
private int max;
public RolloverCounter(int a){
if(a<0){
max = a;
}
}
public void increment()
{
for(int i=0;i<=max;i++)
{
counter++;
System.out.println(counter);
if(counter==max){
counter=0;
}
}
}
public void decrement(){
for(int i=0;i<=max;i++)
counter--;
if(counter<0)
{
counter=max;
}
System.out.println(counter);
}
public String toString() {
return counter;
}
public void reset(){
counter = 0;
}
}
}
What have I done wrong?
Your toString() method isn't returning a String,
public String toString() {
return counter;
}
should be something like
public String toString() {
return String.valueOf(counter);
}
Finally, you appear to have an extra closing brace (at the end) in your code as posted.
I have written the code:
public int compareTo(Object w) {
//w = (Word)w
if(this.count > (Word) w.getCount()) {
return -1;
} else if (this.count < (Word) w.getCount()) {
return 1;
} else {
return 0;
}
}
I have written the class Word. It implements Comparable so I must use the Object parameter for the compareTo() method.
However, I need the object to use a method in the Word class. I get an error if I cast and was wondering if I am doing something wrong or if I need to try something else?
Word class:
package comp10152_lab3;
public class Word implements Comparable{
private int count;
private String word;
public Word(String word) {
this.word = word;
this.count = 1;
}
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
public String getWord() {
return word;
}
public void setWord(String word) {
this.word = word;
}
#Override
public int compareTo(Object w) {
if(this.count > w.getCount()){
return -1;
}
else if (this.count < w.getCount()) {
return 1;
}
else {
return 0;
}
}
public void countUp() {
count++;
}
#Override
public String toString() {
return word + "(" + count + ")";
}
#Override
public boolean equals(Object w) {
return w.equals(word);
}
}
The equals class is suppose to be that way, as per instruction.
The error I am getting is on the w.getCount() which is a "missing symbol" error.
This is the code that you need:
public int compareTo(Object o) {
Word w = (Word) o;
if(this.count > w.getCount()){
return -1;
}
else if (this.count < w.getCount()) {
return 1;
}
else {
return 0;
}
}
The problem that you were having was due to the fact that w was of the type Object, the statement w = (Word) w would not do what you wanted. The second part of the problem has to do with the precedence of the cast operator in Java. When you do (Word)w.getCount(), the getCount() part gets evaluated first, meaning that you were effectively doing (Word) <some int>. What you could have done was wrap it in parentheses like ((Word) w).getCount() to solve that problem.
You should implement Comparable<Word> so that the compareTo method is public int compareTo(Word w). Also you can simplify your compareTo code:
public class Word implements Comparable<Word> {
private int count;
public int compareTo(Word w) {
return w.count - this.count;
}
}
If you can't use java generics then you can still do your compareTo in one line:
public int compareTo(Object w) {
return ((Word) w).count - this.count;
}
Okay I have a really annoying error. Its coming from my retainAll method. The problem is that I am outputting 1,3,5 in ints at the end, but I need 1,3,5,7,9. Here is the code below for the MySet and driver classes
public class MySetTester {
public static void main(String[]args) {
MySet<String> strings = new MySet<String>();
strings.add("Hey!");
strings.add("Hey!");
strings.add("Hey!");
strings.add("Hey!");
strings.add("Hey!");
strings.add("Listen!");
strings.add("Listen!");
strings.add("Sorry, I couldn't resist.");
strings.add("Sorry, I couldn't resist.");
strings.add("(you know you would if you could)");
System.out.println("Testing add:\n");
System.out.println("Your size: " + strings.size()
+ ", contains(Sorry): " + strings.contains("Sorry, I couldn't resist."));
System.out.println("Exp. size: 4, contains(Sorry): true\n");
MySet<String> moreStrings = new MySet<String>();
moreStrings.add("Sorry, I couldn't resist.");
moreStrings.add("(you know you would if you could)");
strings.removeAll(moreStrings);
System.out.println("Testing remove and removeAll:\n");
System.out.println("Your size: " + strings.size()
+ ", contains(Sorry): "
+ strings.contains("Sorry, I couldn't resist."));
System.out.println("Exp. size: 2, contains(Sorry): false\n");
MySet<Integer> ints = new MySet<Integer>();
for (int i = 0; i < 100; i++) {
ints.add(i);
}
System.out.println("Your size: " + ints.size());
System.out.println("Exp. size: 100\n");
for (int i = 0; i < 100; i += 2) {
ints.remove(i);
}
System.out.println("Your size: " + ints.size());
System.out.println("Exp. size: 50\n");
MySet<Integer> zeroThroughNine = new MySet<Integer>();
for (int i = 0; i < 10; i++) {
zeroThroughNine.add(i);
}
ints.retainAll(zeroThroughNine);
System.out.println("ints should now only retain odd numbers"
+ " 0 through 10\n");
System.out.println("Testing your iterator:\n");
for (Integer i : ints) {
System.out.println(i);
}
System.out.println("\nExpected: \n\n1 \n3 \n5 \n7 \n9\n");
System.out.println("Yours:");
for (String s : strings) {
System.out.println(s);
}
System.out.println("\nExpected: \nHey! \nListen!");
strings.clear();
System.out.println("\nClearing your set...\n");
System.out.println("Your set is empty: " + strings.isEmpty());
System.out.println("Exp. set is empty: true");
}
}
And here is the main code. But still read the top part because that's where my examples are.
import java.util.Set;
import java.util.Collection;
import java.lang.Iterable;
import java.util.Iterator;
import java.util.Arrays;
import java.lang.reflect.Array;
public class MySet<E> implements Set<E>, Iterable<E>
{
// instance variables - replace the example below with your own
private E[] backingArray;
private int numElements;
/**
* Constructor for objects of class MySet
*/
public MySet()
{
backingArray=(E[]) new Object[5];
numElements=0;
}
public boolean add(E e){
for(Object elem:backingArray){
if (elem==null ? e==null : elem.equals(e)){
return false;
}
}
if(numElements==backingArray.length){
E[] newArray=Arrays.copyOf(backingArray,backingArray.length*2);
newArray[numElements]=e;
numElements=numElements+1;
backingArray=newArray;
return true;
}
else{
backingArray[numElements]=e;
numElements=numElements+1;
return true;
}
}
public boolean addAll(Collection<? extends E> c){
for(E elem:c){
this.add(elem);
}
return true;
}
public void clear(){
E[] newArray=(E[])new Object[backingArray.length];
numElements=0;
backingArray=newArray;
}
public boolean equals(Object o){
if(o instanceof Set &&(((Set)o).size()==numElements)){
for(E elem:(Set<E>)o){
if (this.contains(o)==false){
return false;
}
return true;
}
}
return false;
}
public boolean contains(Object o){
for(E backingElem:backingArray){
if (o!=null && o.equals(backingElem)){
return true;
}
}
return false;
}
public boolean containsAll(Collection<?> c){
for(E elem:(Set<E>)c){
if(!(this.contains(elem))){
return false;
}
}
return true;
}
public int hashCode(){
int sum=0;
for(E elem:backingArray){
if(elem!=null){
sum=sum+elem.hashCode();
}
}
return sum;
}
public boolean isEmpty(){
if(numElements==0){
return true;
}
else{
return false;
}
}
public boolean remove(Object o){
int i=0;
for(Object elem:backingArray){
if(o!=null && o.equals(elem)){
backingArray[i]=null;
numElements=numElements-1;
E[] newArray=Arrays.copyOf(backingArray,backingArray.length-1);
return true;
}
i=i+1;
}
return false;
}
public boolean removeAll(Collection<?> c){
for(Object elem:c){
this.remove(elem);
}
return true;
}
public boolean retainAll(Collection<?> c){
MySet<E> removalArray=new MySet<E>();
for(E arrayElem:backingArray){
if(arrayElem!= null && !(c.contains(arrayElem))){
this.remove(arrayElem);
}
}
return false;
}
public int size(){
return numElements;
}
public <T> T[] toArray(T[] a) throws ArrayStoreException,NullPointerException{
for(int i=0;i<numElements;i++){
a[i]=(T)backingArray[i];
}
for(int j=numElements;j<a.length;j++){
a[j]=null;
}
return a;
}
public Object[] toArray(){
Object[] newArray=new Object[numElements];
for(int i=0;i<numElements;i++){
newArray[i]=backingArray[i];
}
return newArray;
}
public Iterator<E> iterator(){
setIterator iterator=new setIterator();
return iterator;
}
private class setIterator implements Iterator<E>{
private int currIndex;
private E lastElement;
public setIterator(){
currIndex=0;
lastElement=null;
}
public boolean hasNext(){
while(currIndex<=numElements && backingArray[currIndex]==null){
currIndex=currIndex+1;
}
if (currIndex<=numElements){
return true;
}
return false;
}
public E next(){
E element=backingArray[currIndex];
currIndex=currIndex+1;
lastElement=element;
return element;
}
public void remove() throws UnsupportedOperationException,IllegalStateException{
if(lastElement!=null){
MySet.this.remove((Object)lastElement);
numElements=numElements-1;
}
else{
throw new IllegalStateException();
}
}
}
}
I've been able to reduce the problems, but otherwise this thing is still causing problems.
Bug in the remove method. I added my implementation this method:
public boolean remove(Object o) {
int i = 0;
for (Object elem : backingArray) {
if (o != null && o.equals(elem)) {
System.arraycopy(backingArray, i+1, backingArray, i, numElements-i-1);
backingArray[numElements-1] = null;
numElements = numElements - 1;
return true;
}
i = i + 1;
}
return false;
}
and another bug in method retainAll. I added my implementation this method:
public boolean retainAll(Collection<?> c) {
int index = 0;
boolean result = false;
if (this.containsAll(c)){
result = true;
}
while(index < numElements) {
E e = backingArray[index];
if (e != null && !(c.contains(e))) {
this.remove(e);
} else {
index++;
}
}
return result;
}
Question is answered #frostjogla. Adding one more. If you've checked the actual content of backingArray each time, you could have noticed the issue earlier.
You can do it by overwriting the toString method like
#Override
public String toString() {
StringBuilder sb = new StringBuilder();
for (E backingElem : backingArray) {
sb.append(" ").append(backingElem);
}
return sb.toString();
}
and print by
System.out.println("Contents of MySet " + ints);