Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I'm trying to create a method in java which compares some products. I need to compare them by unit of measure and then by quantity, but I don't know how. I need to use object.equals ?
I'll put my code here.
public abstract class Produs implements Comparable {
private String tipProdus;
private String unitateMasura;
private int cantitate;
public Produs(String tipProdus, String unitateMasura, int cantitate) {
super();
this.tipProdus = tipProdus;
this.unitateMasura = unitateMasura;
this.cantitate = cantitate;
}
public Object genereazaDescriere() {
Object String = null;
return String;
}
public void compareTo() {
tipProdus.equals(unitateMasura);{
}
}
}
First of all, you can not create objects from an abstract class so you need to change that or just forget about that constructor because you won't be able to use it.
To compare two objects you need to create a comparator class so you would be able to compare objects according to the attributte you want to.
So in this case you need to create two comparators, one to compare them by unit of measure and another to compare it by quantity.
So it would be something like this:
Comparator by unit of measure:
public class UnitOfMeasureProdusComparator implements Comparator<Produs> {
#Override
public int compare(Produs p1, Produs p2) {
return p1.getUnitateMasura().compareTo(p2.getUnitateMasura());
}
Comparator by quantity:
public class QuantityProdusComparator implements Comparator<Produs> {
#Override
public int compare(Produs p1, Produs p2) {
return p1.getCantitate().compareTo(p2.getCantitate());
}
So now for example if you have an arraylist of Produs objects you can compare them like this:
ArrayList<Produs> products = new ArrayList<>();
Produs p1 = new Produs("x", "centimeters", 5);
Produs p2 = new Produs("y", "meters", 4);
products.add(p1,p2);
//now you have two objects created so if you want to sort them by there quantity u can do it like this:
Collections.sort(productos, new QuantityProdusComparator());
It will sort the list according to the comparator you use.
Internally the comparator class will send a 0 if the objects are equal, a -1 if the object is smaller than or a 1 if the object is bigger than.
If you comparing string attributes it will do it in alphabetical order.
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
The community is reviewing whether to reopen this question as of 1 year ago.
Improve this question
I am pretty new at Java, so please bear with me.
So I have a class with a generic for both the bag class and interface class as I have to have two bags: one that contains strings, and another that contains doubles (it could also be floats as an alternate, if that would work better with the program). How would I go about writing in the bag class and interface a way to add up the second bag with doubles or floats in it in order to get a total value that the bag holds?
If your Bag class can hold things that aren't numbers, then giving it a method to add its contents together isn't appropriate.
Let's say your Bag interface looks like:
interface Bag<T> {
void add(T item);
Iterator<T> items();
}
If we want to add a method to sum the contents of a bag of Doubles it would look like:
interface Bag<T> {
...
double sum();
...
}
How could we implement that?
class BagImpl<T> implements Bag<T> {
private List<T> contents; // or however we store the members internally
double sum() {
double total = 0.0;
for (T t: contents) {
total = total + ??? // how do we turn T into a number?
}
return total;
}
There is no general way to treat an instance of Object as a number, and we don't know anything about T other than that it is a subclass of Object.
But the concept of being able to apply some function which combines elements of our Bag into a single value is a useful one.
You could give the Bag interface a method to 'reduce' its contents to a single value:
interface Bag<T> {
...
T reduce(T initial, BiFunction<T,T> f);
...
}
so summing over the Bag would be done:
double t = bag.reduce(0.0, (a,b) -> a + b);
And the implementation of reduce would be something like:
public T reduce(T initial, BiFunction<T,T> f) {
T finalValue = initial;
for (T t : contents) {
finalValue = f.apply(finalValue, t);
}
return finalValue;
}
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I have a class which contain called books which contains 3 variables.
String name;
int price;
int pages;
I need to sort these but cannot use the compare To interface on the book class. Is there a way to sort by name then price then pages?
// create a class for comparing name that implements the comparator interface
class BooknameComparator implements Comparator{
public int compare(Object o1,Object o2){
Student s1=(Student)o1;
Student s2=(Student)o2;
return s1.name.compareTo(s2.name);
}
}
// create a class for comparing price
class PriceComparator implements Comparator{
public int compare(Object o1,Object o2){
Student s1=(Student)o1;
Student s2=(Student)o2;
if(s1.price==s2.price)
return 0;
else if(s1.price>s2.price)
return 1;
else
return -1;
}
}
In your main class ,call the sort method as follows :
// for comparison using name
Collections.sort(al,new BooknameComparator ());
// for comaprison using price
Collections.sort(al,new PriceComparator ());
You can customise your sorting based on your needs and these classes
The answer from Vishsh is the solution to your problem - you don't need to modify the Book class in order to create a comparator based on its fields. I 'll just show the Java 8 syntax for doing this (which is more concise).
Edit
This is how you would sort your books if they were contained in a list:
Collections.sort(bookArray,Comparator.comparing(Book::getName));
Collections.sort(bookArray,Comparator.comparing(Book::getPrice));
Collections.sort(bookArray, Comparator.comparing(Book::getPages));
Now that you have an array, you can use:
Book[] sortedBookArray = Arrays.stream(bookArray).sorted(Comparator.comparing(Book::getPrice)).sorted(Comparator.comparing(Book::getName)).sorted(Comparator.comparing(Book::getPrice)).toArray();
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I am getting ClassCastException error. This error occurs when I insert the object that is derived from a class I have created.
My code is below:
When I run, I always get ClassCastException error.
Also, the comparator of my class is shown as null in debugger.
I have written a comparator (as far as I know) and overridden necessary methods.
How can I use a Set<> with a class that I have created and use contains() method?
public class Person implements Comparable<Person>
{
int age;
double height;
public Person(int age, double height)
{
this.age = age;
this.height = height;
}
#Override
public int compareTo(Person person)
{
return age - person.age;
}
public boolean equals(Object obj)
{
final Person other = (Person) obj;
if (this.age == other.age)
return true;
return false;
}
public static void main(String[] args)
{
Set<Person> people = new HashSet<>();
Person p1 = new Person(10, 1.00);
Person p2 = new Person(11, 1.10);
Person p3 = new Person(12, 1.20);
Person p4 = new Person(14, 1.40);
people.add(p1);
people.add(p2);
people.add(p3);
people.add(p4);
if(people.contains(12))
System.out.println("contains");
else
System.out.println("does not contain");
}
}
I have managed to get rid of the error. But now, the output is "does not contain".
What I am about to suggest has nothing to do with ClassCastException, which is thrown simply because you are checking contains with an int argument on a set of objects of type Person ... short answer: you can't cast an object to a subclass of which it is not an instance. Even the javadoc says exactly that.
For situations like this, I really like to use Guava predicates. A predicate allows you to apply a boolean condition to any iterable, returning those elements that satisfy the specified condition. In your example, you can define predicates that return the subset of people of whatever age you want.
Predicate<Person> getAgePredicate(final int age) {
return new Predicate<Person>() {
public boolean apply(Person p) { return p.age == age; }
};
}
Set<Person> people = new Hashset<>();
... // populate people
Set<Person> peopleOfAgeTwelve = Sets.filter(people, getAgePredicate(12));
Hope this helps.
I assume that your class Adjacent implements Comparable interface based on your code. And your class contains a method called getID(). So therefore when you override the compareTo() method, you want to make sure that the object comparison makes sense. I'm not sure what your getID() returns. But it seems like integer. So you might want to change the implementation of compareTo() as follows:
#Override
public int compareTo(Adjacent adj) {
return this.getId() - adj.getId();
}
So this way the comparison will return negative/zero/positive depending on the ID comparison of two Adjacent class objects.
Also in your overrided equals() method, the implementation is incorrect because two objects are not necessarily equal even if they have the same hash code. A good example of overriding equals and hashCode methods is given in another SO post. Also, in your case, I think you probably don't even need to override equals method since your class implements Comparable interface already.
Don't call contains with a parameter that's a different type; this behavior is actually documented. The contains() method is a non-generic method for legacy reasons, and it's not safe if you're using a TreeSet. If you implement hashCode() and equals() and switch to a HashSet, your problems will go away.
Do you really need people sorted by age?
Edit: I see what you're trying to do, now. You don't want a Set, you want Map<Integer, Collection<Person>>, or just a single pass loop to look for the given age.
for (Person p : people) {
if (p.age == 12) ...;
}
or
Map<Integer, Set<Person> peopleByAge = new HashMap<Integer, Set<Person>>();
for (Person p : people) {
if (!peopleByAge.contains(p.age)) {
peopleByAge.put(p.age, new TreeSet<Person>();
}
peopleByAge.get(p.age).add(p);
}
if (people.age.containsKey(12)) ...
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
Are there any alternatives to? (1 group )
class team {
List<String> team = new ArrayList<String>
int score = 0;
}
Is there an object that that store a List or Set 'String', that can hold a value of a Integer?
Thanks in advance.
It sounds like you need a Score object:
class Score
{
int points;
String groupName;
}
and then a List<Score> of them
What you probably want is a new type that holds both the String and the int that you care about, e.g.:
public class Score {
String group;
int score;
}
...
List<Score> scores = new ArrayList<Score>();
To answer your original question, though: The narrowest common type between String and Integer is Object, and you can construct such a List:
List<Object> group = new ArrayList<Object>();
group.add("string");
group.add(1);
Of course, this isn't restrictive to just String and Integer types, you can add any type of object.
Alternatively, you could coerce your Integer into a String:
String someNumber = String.valueOf(1);
Or construct a new class that is more restrictive, and acts as a kind of union:
public class StringOrInteger {
private final Object value;
public StringOrInteger(String string) {
value = string;
}
public StringOrInteger(Integer integer) {
value = integer;
}
public Object getValue() {
return value;
}
}
...and then have a list of these:
List<StringOrInteger> group = new ArrayList<StringOrInteger>();
(which will be at least compile-time restrictive)
You could get fancier with the class, and make it so that it returns a correctly cast object, but I suppose it depends on your use-case where you want to go with this.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I would like to create a sorted set with some sample data using CompareTo.
Can you provide some sample coding on how to do this?
You need a compareTo method in your class that you want to compare with others, and have the class implement comparable:
public class TestObject implements Comparable{
private int a_number;
public int getNumber() {
return a_number;
}
public int compareTo(TestObject other) {
return getNumber() - other.getNumber();
}
}
You can now compare objects of this class with objects of the same class
List<MyObject> list = new List<MyObject>()
......
Collections.sort(list, new Comparator<MyObject>(){
public int compare(MyObject o1, MyObject o2) {
return o1.myValue.compareTo(o2.myValue);
}
});
I would start by reading
http://docs.oracle.com/javase/7/docs/api/java/lang/Comparable.html
and then reading how to use it in TreeSet
http://docs.oracle.com/javase/7/docs/api/java/util/TreeSet.html