Sorting an array with out the compareTo method [closed] - java

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();

Related

java-project -Comparable Interface [closed]

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.

How to make an arraylist that stores infomration from 3 different classes [closed]

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 4 years ago.
Improve this question
I have an assignment where I need to make a program that stores student information. I need to apply concepts of inheritance and interfaces.
I need to create an Arraylist that stores info from 3 different classes. Attached is the program description and features. I want a general idea of what I need to do to implement this program.cord
Create objects list
List<Object> objects = new ArrayList<>();
Add different objects to the objects list:
objects.add(1232);
objects.add("Some string");
objects.add(122.212f);
Check element type with for loop:
for (Object obj : objects) {
if (obj.getClass() == String.class) {
System.out.println(" string :- " + obj);
}
if (obj.getClass() == Integer.class) {
System.out.println(" int :- " + obj);
}
if (obj.getClass() == Float.class) {
System.out.println(" float :- " + obj);
}
}
Create a super class or an interface with a meaningful name that is related to those all 3 classes and then extend that super class or implement that interface to each of these classes .
When you create a list put the super class type or the interface type in the list.
You should create a common superclass for all informatio so you can use it as a type:
List<YourSuperclass>
But conisdering your task, you should follow composition over inheritance:
public class Student {
private List<Course> courses;
private String name;
...
}
So you could do:
List<Student> students
Then you could find the courses of a student:
students.get(0).getCourses()

How to sort object array in ascending order based on instance variables [closed]

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 6 years ago.
Improve this question
I'm trying to sort an object array in Java. I have created for example:
Employee[] hourly = new Employee[];
Then had the user input values for the name, id, hourly pay. Such as ask
System.out.println("Please enter employee name, id and hourly pay");
Then storing the name as a sting id as int and hourly pay as double. From there I needed to sort the object array Employee by hourly pay in ascending order.
I want to do this without comparator or array list.
I want to do this without comparator or array list.
You can either let your Employee class implements Comparable then sort it with Arrays.sort(employeeArray);
public class Employee implements Comparable<Employee>
{
//Constructors and other members not shown
#Override
public int compareTo(Employee e){
return (getHourlyPay() - e.getHourlyPay());
}
}
Arrays.sort(employeeArray);
OR
Implement your own sorting method where you sort according to the hourly pay of each employee object. The way how you sort it will be similar to sorting an integer array.
For example, instead of writing..
if (array[i] < min) //where array[i] is of type int
you will be writing..
if(employee[i].getHourlyPay() < min)

Java Comparator Related [closed]

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 am new to Java so wanted to confirm that can we have different type of objects
in compare method while implementing comparator interface.
Like. compare(Employee ,Department). or evertime we will pass same type of object Ex, Either Employee or Department. It will be helpful for me if you give answer in details.
Please confirm me .Thanks in Advance
Shahid
You can implement a method like:
int compare(Object a, Object b);
and compare oranges to apples if you wish. If you need to be a bit more strict, you can (should!) define something that the compared object need to have in common. Then you can start with an interface:
public interface CorporateObject
{
int getUselesnessFactor();
}
and then make both your Employee and Department classes implement it:
public class Employee implements CorporateObject
{...
public class Department implements CorporateObject
{...
Finally, the compare method would look like:
public int compare(CorporateObject a, CorporateObject b){
if(a.getUselesnessFactor() < b.getUselesnessFactor()) return -1;
if(a.getUselesnessFactor() > b.getUselesnessFactor()) return 1;
return 0;
}
You would be using this method like this:
int result;
Employee boss = new Employee();
Employee john = new Employee();
Department nosepickers = new Departement();
Department slackmasters = new Department();
result = compare(boss, john); // employee to employee
result = compare(nosepickers, slackmasters); // dept to dept
result = compare(boss, nosepickers); // employee to dept
result = compare(slackmasters, john); // dept to employee
etc.

Looking to create and add sample data into a sorted set using CompareTo [closed]

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

Categories