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);
}
}
Related
I am trying to build an ArrayList that will contain objects. when i add an object to the list i want it to first check the array list for that object. and if it finds it i want it to increase a quantity variable in that object and not create a new object in the list. and then vice versa when removing objects. I have accomplished a way that works when removing an object. But i dont think i fully understand the methods in the arraylist or the logic when creating and arraylist of objects. as when i use .contains or .equals im not getting the desired effect.
public class ItemBag {
private ArrayList<Item> inventory = new ArrayList<Item>();
public ItemBag() {
}
public void addItem(Item objName, int quantity) {
if (inventory.contains(objName)) {
System.out.println("if statement is true!");
int i = inventory.indexOf(objName);
inventory.get(i).setQuantity(inventory.get(i).getQuantity() + quantity);
} else {
inventory.add(objName);
objName.setQuantity(quantity);
}
}
public void removeItems(String itemName, int quantiy) {
for (int i = 0; i < inventory.size(); i++) {
if (inventory.get(i).name() == itemName) {
inventory.get(i).setQuantity(inventory.get(i).getQuantity() - quantiy);
if (inventory.get(i).getQuantity() <= 0) {
inventory.remove(inventory.get(i));
}
}
}
}
public void showInventory() {
for (int i = 0; i < inventory.size(); i++) {
System.out.println(inventory.get(i).name() + " : " + inventory.get(i).getQuantity());
}
}
then when creating the itemBag in another object i am writing
ItemBag merchantItems = new ItemBag();
public void merchantBob() {
merchantItems.addItem(new HealthPotion() ,3);
merchantItems.showInventory();
System.out.println("add 1");
merchantItems.addItem(new HealthPotion(),1);
merchantItems.showInventory();
Items class
package Items;
public abstract class Item {
private int quantity = 0;
public Item() {
}
public abstract String name();
public abstract int cost();
public abstract String type();
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
}
HealthPotion Class
public class HealthPotion extends Potions {
protected int addHealth = 10;
#Override
public int drinkPotion() {
return addHealth;
}
#Override
public String name() {
return "Health Potion";
}
#Override
public int cost() {
return 5;
}
#Override
public String type() {
return "Potion";
}
}
The .contains() method would iterate through the list and use .equals() method to compare each element and check if the provided object exists in the list.
.equals() method would compare the object reference (unless .equals() is overridden) to check if the objects are same.
For reference: https://docs.oracle.com/javase/8/docs/api/java/util/Collection.html#contains-java.lang.Object-
You can override the .equals() method to compare the values of the provided object in the following way:
public abstract class Item {
private int quantity = 0;
public Item() {
}
public abstract String name();
public abstract int cost();
public abstract String type();
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
#Override
public boolean equals(Object object) {
if (this == object) return true;
if (object == null || getClass() != object.getClass()) return false;
Item providedItem = (Item) object;
return name == providedItem.name
&& cost == providedItem.cost
&& type == providedItem.type;
}
}
This should work
This question already has answers here:
How do define my own element class for use with Set
(2 answers)
Why should a Java class implement comparable?
(10 answers)
Closed 6 years ago.
I have a simple class called Stock the code is listed below, and I my requirement is to create a Collection of Stock where the combination of the fields StockId, Code and name should be unique, I am doing this by implementing my own list class. I was wondering if there is any better way to do this
public class Stock {
private Integer stockId;
private String stockCode;
private String stockName;
public Stock() {
}
public Stock(Integer stockId,String stockCode, String stockName) {
this.stockCode = stockCode;
this.stockName = stockName;
}
public Integer getStockId() {
return this.stockId;
}
public void setStockId(Integer stockId) {
this.stockId = stockId;
}
public String getStockCode() {
return this.stockCode;
}
public void setStockCode(String stockCode) {
this.stockCode = stockCode;
}
public String getStockName() {
return this.stockName;
}
public void setStockName(String stockName) {
this.stockName = stockName;
}
}
List class
public class StockList {
private List<Stock> listStock;
public StockList(){
listStock = new ArrayList<Stock>();
}
public void add(Stock stock){
boolean result=true;
for(Stock st:listStock){
int count=0;
if(st.getStockId()==stock.getStockId()){
count++;
}
if(st.getStockCode()==stock.getStockCode()){
count++;
}
if(st.getStockName()==stock.getStockName()){
count++;
}
if(count>=3){
result=false;
break;
}
}
if(result) {
listStock.add(stock);
}
}
public List<Stock> getList(){
return listStock;
}
}
I have even tried the Hashset per instructions but it still let me add two Stock objects with same values in every field
import java.util.HashSet;
import java.util.Set;
public class Stock {
private Integer stockId;
private String stockCode;
private String stockName;
public Stock() {
}
public Stock(Integer stockId,String stockCode, String stockName) {
this.stockCode = stockCode;
this.stockName = stockName;
}
public Integer getStockId() {
return this.stockId;
}
public void setStockId(Integer stockId) {
this.stockId = stockId;
}
public String getStockCode() {
return this.stockCode;
}
public void setStockCode(String stockCode) {
this.stockCode = stockCode;
}
public String getStockName() {
return this.stockName;
}
public void setStockName(String stockName) {
this.stockName = stockName;
}
public int hashCode() {
final int PRIME = 31;
int result = 1;
result = PRIME * result + stockId+stockCode.hashCode()+stockName.hashCode();
return result;
}
public boolean equals(Object obj) {
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
final Stock other = (Stock) obj;
int count=0;
if (stockId == other.stockId){
count++;
}
if(stockCode.equalsIgnoreCase(other.stockCode)){
count++;
}
if(stockName.equalsIgnoreCase(other.stockName)){
count++;
}
if(count<3) {
return true;
}
return false;
}
}
You will need to add your Stock objects in a HashSet<Stock>.
Before adding a Stock object to the set, you will be able to check whether the HashSet already contains it by invoking myStockHashSet.contains( stock ). (But even if you go ahead and add a duplicate stock object to the HashSet, the new object will not replace the old object, so there will never be duplicates.)
In order for HashSet to work, it has to be able to tell whether two Stock objects are identical. For this, your Stock class will need to implement hashCode() and equals().
hashCode() will need to hash together the fields stockId, code and name. Recent versions of java offer an Objects.hashCode( Object ... ) convenience method for quickly hashing together your fields. If you are not programming against a recent version of java, you will need to write your own implementation of a hashCode() calculation. Look here for some good advice: Best implementation for hashCode method
equals() should return true only if all these fields are equal in both objects.
NOTE:
do not waste your time with a List, since lists allow duplicates.
do not waste your time implementing Comparable, since this is for ordering objects, not for comparing objects for equality, and HashSet does not care whether your objects implement Comparable.
I have got an array of 20:
private Karte[] deckArr;
deckArr = new Karte[20];
Now I want to sort the array by card-names every time a new card is added.
P.S. the cards are added 1 by 1 after clicking on a button, so there are empty spaces in the array.
Since the...
Arrays.sort(deckArr.getName());
...method does not work here I asked myself how it is done.
Karte(card) class:
package Model;
/**
* Created by 204g07 on 18.03.2016.
*/
public class Karte implements ComparableContent<Karte>{
private int schoenheit;
private int staerke;
private int geschwindigkeit;
private int intelligenz;
private int coolness;
private int alter;
private String seltenheit;
private String name;
public Karte(String pName, int pSchoenheit,int pStaerke,int pGeschwindigkeit, int pIntelligenz, int pCoolness, int pAlter, String pSeltenheit ) {
name=pName;
schoenheit=pSchoenheit;
staerke=pStaerke;
geschwindigkeit=pGeschwindigkeit;
intelligenz=pIntelligenz;
coolness=pCoolness;
alter=pAlter;
seltenheit=pSeltenheit;
}
//getter
public int getSchoenheit(){
return schoenheit;
}
public int getStaerke(){
return staerke;
}
public int getGeschwindigkeit(){
return geschwindigkeit;
}
public int getIntelligenz(){
return intelligenz;
}
public int getCoolness(){
return coolness;
}
public int getAlter(){
return alter;
}
public String getSeltenheit(){
return seltenheit;
}
public String getName(){
return name;
}
//setter
public void setSchoenheit(int pSchoenheit){
schoenheit = pSchoenheit;
}
public void setStaerke(int pStaerke){
staerke = pStaerke;
}
public void setGeschwindigkeit(int pGeschwindigkeit){
geschwindigkeit = pGeschwindigkeit;
}
public void setIntelligenz(int pIntelligenz){
intelligenz = pIntelligenz;
}
public void setCoolness(int pCoolness){
coolness = pCoolness;
}
public void setAlter(int pAlter){
alter = pAlter;
}
public void setSeltenheit(String pSeltenheit){
seltenheit = pSeltenheit;
}
public void setName(String pName){
name = pName;
}
#Override
public boolean isLess(Karte karte) {
if (getName().compareTo(karte.getName()) < 0){
return true;
}else{
return false;
}
}
#Override
public boolean isEqual(Karte karte) {
return getName() == karte.getName();
}
#Override
public boolean isGreater(Karte karte) {
if (getName().compareTo(karte.getName()) > 0){
return true;
}else{
return false;
}
}
}
Any help is appreciated!
Why not just use ArrayList instead? Easier to add, remove elements and you will never have empty slots.
Anyway to sort you can use Collections.sort like this:
deckArr = new ArrayList<Karte>();
Collections.sort(deckArr, Comparator.comparing(karte -> karte.getName()));
Java 8 offers a simple solution:
The Comparable Interface has a static method that creates a Comaprator with an extractor.
Comparator<Card> comp = Comparator.comparing(Karte::getName);
With this using a sorting method (e.g. Arrays.sort) is easy to call.
On top of that, to solve your nullpointer problem, the Comparator Interface offers another two functions: NullsLast and nullsFirst.
Comparator<Card> comp = Comparator.nullsLast(Comparator.comparing(Card::getName));
For me this looks like the easiest solution to your question :)
This should solve your problem. Implements the Comparable interface.
/**
* Created by 204g07 on 18.03.2016.
*/
public class Karte implements Comparable<Karte>{
private int schoenheit;
private int staerke;
private int geschwindigkeit;
private int intelligenz;
private int coolness;
private int alter;
private String seltenheit;
private String name;
public Karte(String pName, int pSchoenheit,int pStaerke,int pGeschwindigkeit, int pIntelligenz, int pCoolness, int pAlter, String pSeltenheit ) {
name=pName;
schoenheit=pSchoenheit;
staerke=pStaerke;
geschwindigkeit=pGeschwindigkeit;
intelligenz=pIntelligenz;
coolness=pCoolness;
alter=pAlter;
seltenheit=pSeltenheit;
}
//getter
public int getSchoenheit(){
return schoenheit;
}
public int getStaerke(){
return staerke;
}
public int getGeschwindigkeit(){
return geschwindigkeit;
}
public int getIntelligenz(){
return intelligenz;
}
public int getCoolness(){
return coolness;
}
public int getAlter(){
return alter;
}
public String getSeltenheit(){
return seltenheit;
}
public String getName(){
return name;
}
//setter
public void setSchoenheit(int pSchoenheit){
schoenheit = pSchoenheit;
}
public void setStaerke(int pStaerke){
staerke = pStaerke;
}
public void setGeschwindigkeit(int pGeschwindigkeit){
geschwindigkeit = pGeschwindigkeit;
}
public void setIntelligenz(int pIntelligenz){
intelligenz = pIntelligenz;
}
public void setCoolness(int pCoolness){
coolness = pCoolness;
}
public void setAlter(int pAlter){
alter = pAlter;
}
public void setSeltenheit(String pSeltenheit){
seltenheit = pSeltenheit;
}
public void setName(String pName){
name = pName;
}
public int compareTo(Karte karte) {
return this.name.compareTo(karte.getName());
}
}
Then you just need to call Arrays.sort(deckArr);
You need to check for nulls and just call below--
Arrays.sort(deckArr, new Comparator<Karte>() {
#Override
public int compare(Karte karte1, Karte karte2) {
if (karte1.getName() == null && karte2.getName() == null) {
return 0;
}
if (karte1.getName() == null) {
return 1;
}
if (karte2.getName() == null) {
return -1;
}
return karte1.getName().compareTo(karte2.getName());
}});
I was wondering how do I go about to create 2 methods,
1. Which does the checking, if the object already exists within the array (based on one of the parameters).
2. Secondly add a method which allows the user / me to add objects into the array when the previous (1st method) returns false.
Here is my try:
public class Book {
String name;
int isbn;
public Book(String e, int iNr) throws LibraryException{
if(e.equals("")){
throw new LibraryException("Blank / empty name is not allowed!");
}
else if(iNr < 1 || iNr > 9000){
throw new LibraryException("The isbn number is outside the allowed range (1 - 9000)! ");
}
setName(e);
setIsbn(iNr);
}
public boolean equals(Object obj){
if(obj instanceof Book){
isbn = (isbn)obj;
return true;
}
return false;
}
public String getName() {
if(name == null || name == ""){
System.out.print("Does not exist!");
}
return name;
}
public void setName(String name) {
this.name = name;
}
public int getIsbn() {
if(isbn < 0){
System.out.print("ISBN (LIBRI) EXCEPTION TO BE ADDED!");
}
return isbn;
}
public void setIsbn(int isbn) {
this.isbn = isbn;
}
}
.
public class Library
{
String name;
Book[] books;
int nrBooks = 0;
public Library(String name, int nrBooks) throws LibraryException {
if(name.equals("")){
throw new LibraryException("Blank names is not allowed");
}
if(nrBooks < 500){
throw new LibraryException("The number of books needs to be greater than 500!");
}
this.name = name;
this.nrBooks = nrBooks;
this.books = new Book[nrBooks];
}
public void addBook(Book book) throws LibraryException {
if(indexOf(book) == -1){
if(nrBooks < books.length)
books[nrBooks++] = book;
}
}
private int indexOf(Book book)throws LibraryException {
if(nrBooks < Book[].length){
}
return -1;
}
public static void main(String[]args) throws LibraryException{
Library b = new Library("Sami Frasheri", 700);
b.addBook(new Book("Paul Colhen - Alchemist", 1));
b.addBook(new Book("Paul Colhen - Winners Stand ALone", 2));
b.addBook(new Book("Paul Colhen - The river Piedra I sat and I cried", 3));
System.out.print(b);
}
}
Tried ArrayList In Java?.
They will be able to solve almost all of the problems you are facing. Have a look at contains and add.
Please Note, you must override the hashCode and equals method of your Book object for it to work effectively.
I suggest you use an ArrayList of Book. It will solve all of your problems.
public class Library {
private String name;
private ArrayList<Book> books;
private int maxNumberOfBooks;
public Library(String name, int maxNumberOfBooks) {
this.name = name;
this.maxNumberOfBooks = maxNumberOfBooks;
this.books = new ArrayList<Book>();
}
public void addBook(Book book) {
if (!books.contains(book)) {
books.add(book);
}
}
}
If you need to check both parameters, then do something like:
public void addBook(Book book) {
for (Book b : books) {
if (b.getName().equals(book.getName())) {
return; // another book has the same name
}
if (b.getIsbn() == book.getIsbn()) {
return; // another book has the same ISBN
}
}
books.add(book);
}
The size of an array can't be modified. If you want to add an element, you have to instantiate a new array.
public void addBook(Book book) {
int oldN = books.length;
books = Arrays.copyOf(books, oldN + 1);
books[oldN] = book;
return books;
}
This function could replace indexOf(). It looks for the element in your array.
private boolean contains(Book book) {
for (Book b : books) {
if (b != null && book.equals(b))
return true;
}
return false;
}
I would suggest something like this:
public void addBook(Book book) throws LibraryException {
if(indexOf(book) == -1){//book does not exist
if(nrBooks < (books.length-1)){
books[nrBooks] = book;
++nrBooks;
} else {
throw new LibraryException("Not space for more books.");
}
}
}
private int indexOf(Book book)throws LibraryException {
for(int i=0;i<books.lenght;++i){
if(books[i].getName().equals(book.getName()) && books[i].getIsbn==book.getIsbn){
return i;
}//if
}//for
//else
return -1;
}
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();
}
}