Why is this sort array not working? - java

I have to sort an array here is the code I have. When I try to utilize Arrays.sort() I get tons of errors. Anyone know what I am doing wrong? This is really my first time sorting and using arrays with constructors.
import java.util.Scanner;
import java.util.Arrays;
public class CoffeeDriver {
//main method
public static void main (String[] args){
Item[] itemObject = new Item[] {
new Item("Donut", .75),
new Item("Coffee", 1.00),
new Item("Bagel", 1.25),
new Item("Milk", 1.50),
new Item("Water", 2.00)};
Scanner input = new Scanner(System.in);
String decision;
System.out.println ("Welcome to Wings Coffee Shop");
System.out.println ("We have a great list of tasty items on our menu.");
System.out.println ("Would you like to see these items sorted by");
System.out.println ("name or by price? (n/p): ");
decision = input.nextLine();
sortName(itemObject);
sortPrice(itemObject);
}
//method to sort by item name and display
public static void sortName (Item[] itemObject){
Arrays.sort(itemObject);
System.out.println(itemObject);
}
//method to sort by item price and display
public static void sortPrice (Item[] array){
Arrays.sort(array);
for (int i = 0; i < array.length; i++){
System.out.println (array[i]);
}
}
}
public class Item
{
private String itemName = ""; //setting up the name
private double itemPrice=0.0; //Setting price variable
public Item(String name, double price) //Constructor
{
itemName = name;
itemPrice = price;
}
public String getitemName() //retuns name
{
return itemName;
}
public double getitemPrice() //returns price
{
return itemPrice;
}
public void setitemName(String name) //sets name
{
itemName = name;
}
public void setitemPrice (double price) //sets price
{
itemPrice = price;
}
}

Your Item class doesn't implement compareable. The sort method states: "Furthermore, all elements in the array must be mutually comparable (that is, e1.compareTo(e2) must not throw a ClassCastException for any elements e1 and e2 in the array)."
But since you want to sort by two different things, implementing comparable won't get you very far, it's better to use a Comparator (http://docs.oracle.com/javase/7/docs/api/java/util/Comparator.html).
So your sort by name would look something like this (just replace the method part of compare(Item o1, Item o2) with the criteria you'd like the array to be sorted).
// method to sort by item name and display
public static void sortName(Item[] itemObject) {
Arrays.sort(itemObject, new Comparator<Item>() {
#Override
public int compare(Item o1, Item o2) {
return o1.getitemName().compareTo(o2.getitemName());
}
});
printArr(itemObject);
}
and your sortPrice like that:
// method to sort by item price and display
public static void sortPrice(Item[] array) {
Arrays.sort(array, new Comparator<Item>() {
#Override
public int compare(Item o1, Item o2) {
return Double.compare(o1.getitemPrice(), o2.getitemPrice());
}
});
printArr(array);
}
Also to print your results in a nice legible way it's generally a good idea to overwrite the toString() method in your class so that you can just write System.out.println(item); (toString is called automatically in that case).
Okay to get the content nicely printed we first add a toString() Method to your item class:
#Override
public String toString() {
return itemName + ": " + itemPrice;
}
That will just return the item's name and it's price when called. To print the array's content now nicely we'll just iterate through all it's members:
private static void printArr(Item[] arr) {
for(Item i : arr) {
System.out.println(i); // the same as System.out.println(i.toString()); - Java calls the toString method automatically in this case we you give it an object
}
}
Now we can just call this function everywhere you want to print the contents of an item array, like after sorting them!

Arrays.sort takes a Comparator which is used to perform the sort.
A Comparator used to find the difference between 2 items.
public static void sortName (Item[] itemObject){
Arrays.sort(itemObject, new Comparator<Item>() {
public int compare(Item a, Item b) {
if(a.getitemName() == null){
return b.getitemName() == null ? 0 : -1;
}
return a.getitemName().compareTo(b.getitemName());
}
});
}
public static void sortPrice (Item[] array){
Arrays.sort(array, new Comparator<Item>() {
public int compare(Item a, Item b) {
return Double.compare(a.getitemPrice(), b.getitemPrice());
}
});
}

You need to implement the compareTo method in your Item class, and declare it to implement the Comparable interface.
See How to use Comparable for an example.

Related

How to sort arrays of different datatypes

I am trying to sort candidate names alphabetically while sorting votes gained by candidate,I took two arrays one for names and another for votes,as i sort by votes name array need to sort here i can't make it sort please help
here is my code:
package com.sarga.Swinglearn;
import java.util.Scanner;
public class Project3 {
public static void main(String[] args)
{
int i=0,j=0;
Scanner s=new Scanner(System.in);
System.out.println("Enter number of candidates");
int candcount = Integer.parseInt(s.nextLine());
System.out.println("Enter name of the candiadates");
String names[]=new String[candcount];//create an array
for( i=0;i<names.length;i++)
{
names[i]=s.nextLine();
}
System.out.println("candidates are: ");
for(i=0;i<candcount;i++)
System.out.println(names[i]);
for(i=0;i<candcount;i++)
{
for(j=i;j<candcount;j++)
{
if(names[i].compareTo(names[j])>0)
{
String temp=names[i];
names[i]=names[j];
names[j]=temp;
}
}
}
/*To sort names alphabetically*/
System.out.println("alphabetical order of candidates");
for(i=0;i<candcount;i++)
{
System.out.println(names[i]);
}
System.out.println("Enter number of votes of each candidate");
int votes[]=new int[candcount];
for(i=0;i<candcount;i++)
{
votes[i]=s.nextInt();
System.out.println(names[i]+":"+votes[i]);
}
//sort names based on their votes
System.out.println("List of candidates according to their votes");
//int max= votes[1];
int temp=0;
for(i=0;i<candcount-1;i++)
{
for(j=i;j<candcount;j++)
{
if(votes[i]<votes[j])
{
temp=votes[i];
votes[i]=votes[j];
votes[j]=temp;
}
}
}
for(i=0;i<candcount;i++)
System.out.println(names[i]+":"+votes[i]);
s.close();
}
}
Create a Candidate class:
public class Candidate implements Comparable<Candidate> {
private String name;
private int votes;
public Candidate(String name, int votes) {
this.name = Objects.requireNotNull(name);
this.votes = votes;
}
// Getters and setters
#Override
public int compareTo(Candidate that) {
int c = this.name.compareTo(that.name);
if(c != 0) return c;
return this.votes - that.votes;
}
}
Next create a list of those candidates and sort them:
List<Candidate> clist = new ArrayList<>();
// Add some Candidates to clist
Collections.sort(clist);
you shoul use object oriented paradigm ; create a Candidate class which implements the Comparable interface :
public class Candidate
implements Comparable<Candidate>
{
public String name; /* should use getter and setter */
public int votes; /* idem */
public int compareTo(Candidate other)
{
/* implements the comparison, see Comparable doc */
}
}
Then sort a Candidate array in your main :
Candidate[] candidates = new Candidate[candcount];
/* populates the array */
Arrays.sort(candidates);

How can I use objects in an ArrayList to be able to add or remove them from other bit of storage Java

I need to be able to create a set of inventories which are able to store objects that I choose. I have an ArrayList of the objects I need to be able to store in these inventories which have an "item number", "description" and "price".
My question is, what can I use to create these inventories so the user is able to add or remove items (which all come from the ArrayList of items) into them. The only way I can think it would work is by creating another ArrayList being the inventories but I wouldn't know how to add/remove the objects to them seeing as they're in the ArrayList
I have a main method which is where my ArrayList is and an item class with a constructor, getters, setters and toString.
You can add or remove class objects in ArrayList. Following is an example:
import java.util.ArrayList;
public class InventoryHandler {
public static void main(String[] args) {
Inventory inv1 = new Inventory(1,"item1",10.1);
Inventory inv2 = new Inventory(2,"item2",20.1);
Inventory inv3 = new Inventory(3,"item3",30.1);
ArrayList<Inventory> invs = new ArrayList<Inventory>();
//Adding objects
invs.add(inv1);
invs.add(inv2);
invs.add(inv3);
System.out.println("After adding objects");
for(Inventory inv: invs) {
System.out.println("Item: "+inv.getItemNumber()+" Desc: "+
inv.getItemDescription()+" Price: "+inv.getItemPrice());
}
//Removing objects
invs.remove(inv2);
System.out.println("After removing a object");
for(Inventory inv: invs) {
System.out.println("Item: "+inv.getItemNumber()+" Desc: "+
inv.getItemDescription()+" Price: "+inv.getItemPrice());
}
}
}
class Inventory {
private int itemNumber;
private String itemDescription;
private double itemPrice;
public Inventory(int itemNumber, String itemDescription, double itemPrice) {
this.itemNumber = itemNumber;
this.itemDescription = itemDescription;
this.itemPrice = itemPrice;
}
public int getItemNumber() {
return this.itemNumber;
}
public String getItemDescription() {
return this.itemDescription;
}
public double getItemPrice() {
return this.itemPrice;
}
public void setItemNumber(int newItemNumber) {
this.itemNumber = newItemNumber;
}
public void setItemDescription(String newItemDescription) {
this.itemDescription = newItemDescription;
}
public void setItemPrice(double newItemPrice) {
this.itemPrice = newItemPrice;
}
}

Sorting in arraylist

I am trying to sort the elements present in my arraylist in decreasing order. However, there seems to be some issue in the implementation. I am just a beginner in java, and am trying to use the most easiest method possible to sort.
student temp = new student(user_name,given_name,family_name,tot_marks);
for(int j=0;j<list1.size()-1;j++)
{
for(int k=0;k<list1.size();k++)
{
student sort1 = list1.get(j);
student sort2 = list1.get(k);
if(sort1.tot_marks < sort2.tot_marks)
{
temp.user_name=sort1.user_name;
temp.family_name=sort1.family_name;
temp.given_name=sort1.given_name;
temp.tot_marks=sort1.tot_marks;
sort2.user_name=temp.user_name;
sort2.family_name=temp.family_name;
sort2.given_name=temp.given_name;
sort2.tot_marks=temp.tot_marks;
sort1.family_name=sort2.family_name;
sort1.given_name=sort2.given_name;
sort1.tot_marks=sort2.tot_marks;
list1.add(sort1); //Adding sorted elements to the arraylist.
}
//If marks are same, sort on the basis of username.
else if(sort1.tot_marks == sort2.tot_marks)
{
//Compare usernames whichever is greater.
{
temp.user_name=sort1.user_name;
temp.family_name=sort1.family_name;
temp.given_name=sort1.given_name;
temp.tot_marks=sort1.tot_marks;
sort2.user_name=temp.user_name;
sort2.family_name=temp.family_name;
sort2.given_name=temp.given_name;
sort2.tot_marks=temp.tot_marks;
sort1.family_name=sort2.family_name;
sort1.given_name=sort2.given_name;
sort1.given_name=sort2.given_name;
sort1.tot_marks=sort2.tot_marks;
list1.add(sort1);
}
}
}
}
//Print the sorted list.
for (int i=0;i<list1.size();i++)
{
student display = list1.get(i);
System.out.println(display.tot_marks+","+display.given_name+"
"+display.family_name);
}
You could just do:
Collections.sort(list1, new Comparator<student>() {
#Override
public int compare(student one, student another) {
if (one.tot_marks == another.tot_marks) {
return 0;
}
return one.tot_marks > another.tot_marks ? 1 : -1;
}
});
However a few advices:
Class names like student are not very easy for the eye for java developers. Try using capitalized camel case class names (in this case Student)
Underscores in member names are also not very nice in java, try camel case names (totMarks). Even better is a geter, and setter for it, rather than leaving it public. (getTotMarks(), setTotMarks(int))
Also before doing something like you did, try researching a bit! There is a good chance, somebody else wrote it before you!
In java to sort a List you should use Collections.sort and a Comparator.
Collections.sort(list1, new Comparator<student>() {
public int compare(student a, student b) {
if(a.tot_marks < b.tot_marks)
return -1;
else if (a.tot_marks > b.tot_marks)
return 1;
else
return a.username.compareTo(b.username);
}
});
No need for that. You are adding duplicated to your list.
list1.add(sort1); //Adding sorted elements to the arraylist.
Check your swap logic. It should be:
TEMP = SORT1
SORT1 = SORT2
SORT2 = TEMP
The way to go is to ditch your approach and make your student class implement the Comparable interface: public class student implements Comparable<student>. Also, in Java, class names should start with upper case letters.
Once that you make your class implement this interface, you will be forced to implement the compareTo(student student) method.
In this method, you will implement your comparison logic:
public int compareTo(student student)
{
if(this.marks != student.marks)
{
return Integer.compare(this.marks, student.marks);
}
else
{
return this.name.compareTo(student.name);
}
}
Then, to sort your array, simply call like so:
List<student> students = ...
Collections.sort(students);
The above will call your implementation of the .compareTo and sort the array accordingly.
To Sort the arrayList in descending order please implement the Comparator interface
and as Denis rightly pointed out.Do not duplicate the elements
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class MyArrayListSort {
public static void main(String a[]){
List<Student> list = new ArrayList<Student>();
list.add(new Student("Ram",3000));
list.add(new Student("John",6000));
list.add(new Student("Crish",2000));
list.add(new Student("Tom",2400));
Collections.sort(list,new MyMarkComp());
System.out.println("Sorted list entries: ");
for(Student e:list){
System.out.println(e);
}
}
}
class MyMarkComp implements Comparator{
#Override
public int compare(Student e1, Student e2) {
if(e1.getMarks() < e2.getMarks()){
return 1;
} else {
return -1;
}
}
}
class Student{
private String name;
private int mark;
public Student(String n, int s){
this.name = n;
this.salary = s;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getMarks() {
return mark;
}
public void setMarks(int mark) {
this.mark = mark;
}
public String toString(){
return "Name: "+this.name+"-- Marks: "+this.mark;
}
}

Produce sorted arraylist from unsorted arraylist in 1 interation?

Say I have arraylist A and to compare 2 objects of A I do a.getDistanceFromPlayer() < b.getDistanceFromPlayer().
I want to now have list B which will have all of A's objects, but sorted where the first object is closest to player, and last object is furthest.
What might be the fastest way to do this?
Thanks
Have A implement Comparable and then define the method compareTo(Object other) like so:
public int compareTo(Object other) {
if( this.getDistanceFromPlayer() < other.getDistanceFromPlayer() ) {
return -1;
} else if( this.getDistanceFromPlayer() > other.getDistanceFromPlayer()) {
return 1;
}
return 0;
}
Now you can call Collections.sort() on your list of objects
Use Collections.sort with a custom comparator.
eg.
public class DistanceComparator implements Comparator<Integer>{
#Override
public int compare(YourObject o1, YourObject o2) {
if (o1.getDistanceFromPlayer() > o2.getDistanceFromPlayer())
{
return 1;
}
else if (o1.getDistanceFromPlayer() < o2.getDistanceFromPlayer())
{
return -1;
}
return 0;
}
}
Then in your program, call
Collections.sort(YourArrayInstance, new DistanceComparator())
You should make your class implement Comparable.
Then you can use Collections.sort() to sort your List.
If you want a sorted List AND an unsorted List, you'll have to make a copy.
Another option is to create a Comparator.
If you read the documentation for Collections, you'll see it has two sort methods.
One bases the sort on the objects' compareTo method (ie their "natural order").
The other bases the sort on a Comparator that is passed as the second argument.
Here's a link to another question that provides an example implementation of Comparable:
Example implementation of Comparable
Use a Custom Comparator :
B = Collections.sort(A, new CustomComparator());
public class CustomComparator implements Comparator<ClassA> {
#Override
public int compare(final ClassA a, final ClassA b) {
//Make sure you check that neither a nor b are null..
//..
if (a.getDistanceFromPlayer() < b.getDistanceFromPlayer()) {
return 1;
} else if (a.getDistanceFromPlayer() > b.getDistanceFromPlayer()) {
return -1;
}
return 0;
}
}
You can use a custom Comparator and sort your ArrayList, like this:
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
class Main {
public static class Player {
private final float distance;
public Player (final float position) {
this.distance = position;
}
public float getDistanceFrom () {
return distance;
}
#Override
public String toString() {
return "Player [distance=" + distance + "]";
}
}
public static void main(String[] args) throws Exception {
final ArrayList<Player> players = new ArrayList<Player> ();
players.add (new Player (2));
players.add (new Player (5));
players.add (new Player (-3));
players.add (new Player (1));
Collections.sort(players, new Comparator<Player> () {
#Override
public int compare(Player o1, Player o2) {
final float distance1 = o1.getDistanceFrom();
final float distance2 = o2.getDistanceFrom();
return (int) Math.signum (distance1 - distance2);
}
});
System.out.println(players);
}
}
And a fiddle for it.

Sorting List<> by numeric value

I've got a public List<FriendProfile> friends = new ArrayList<FriendProfile>();. I initialize the friends list by reading the information from the server. The FriendProfile object contains a int called private int userPosition;
Once the friends list has been initialized, I would like to sort the friends list by having the FriendProfile object with the highest userPosition at index 0 of the list and then sort by accordingly, index 1 with the second highest userPosition ...
I guess I could write an sorting algorithm, yet I'm looking for prewritten code (maybe the JDK has some methods to offer?)
Help is appreciated!
Use Collections.sort() and specify a Comparator:
Collections.sort(friends,
new Comparator<FriendProfile>()
{
public int compare(FriendProfile o1,
FriendProfile o2)
{
if (o1.getUserPosition() ==
o2.getUserPosition())
{
return 0;
}
else if (o1.getUserPosition() <
o2.getUserPosition())
{
return -1;
}
return 1;
}
});
or have FriendProfile implement Comparable<FriendProfile>.
Implement Comparable Interface.
class FriendProfile implements Comparable<FriendProfile> {
private int userPosition;
#Override
public int compareTo(FriendProfile o) {
if(this.userPosition > o.userPosition){
return 1;
}
return 0;
}
}
Just Call the Collection.sort(List) method.
FriendProfile f1=new FriendProfile();
f1.userPosition=1;
FriendProfile f2=new FriendProfile();
f2.userPosition=2;
List<FriendProfile> list=new ArrayList<FriendProfile>();
list.add(f2);
list.add(f1);
Collections.sort(list);
The List will be sorted.
Now no need to Boxing (i.e no need to Creating OBJECT using new Operator use valueOf insted with compareTo of Collections.Sort..)
1)For Ascending order
Collections.sort(temp, new Comparator<XYZBean>()
{
#Override
public int compare(XYZBean lhs, XYZBean rhs) {
return Integer.valueOf(lhs.getDistance()).compareTo(rhs.getDistance());
}
});
1)For Deascending order
Collections.sort(temp, new Comparator<XYZBean>()
{
#Override
public int compare(XYZBean lhs, XYZBean rhs) {
return Integer.valueOf(rhs.getDistance()).compareTo(lhs.getDistance());
}
});
Use Collections.Sort and write a custom Comparator that compares based on userPosition.
use Comparator with Collections.sort method
java.util.Collections.sort(list, new Comparator<FriendProfile >(){
public int compare(FriendProfile a, FriendProfile b){
if(a.getUserPosition() > b.getUserPosition()){
return 1;
}else if(a.getUserPosition() > b.getUserPosition()){
return -1;
}
return 0;
}
});
see this link
There are two ways to do this.
1.
FriendProfile could implement the interface Comparable.
public class FriendProfile implements Comparable<FriendProfile>
{
public int compareTo(FriendProfile that)
{
// Descending order
return that.userPosition - this.userPosition;
}
}
...
Collections.sort(friendProfiles);
2.
You could write a Comparator.
public class FriendProfileComparator implements Comparator<FriendProfile>
{
public int compare(FriendProfile fp1, FriendProfile fp2)
{
// Descending order
return fp2.userPosition - fp1.userPosition;
}
}
...
Collections.sort(friendProfiles, new FriendProfileComparator());
When comparing objects rather than primitives note that you can delegate on to the wrapper objects compareTo. e.g. return fp2.userPosition.compareTo(fp1.userPosition)
The first one is useful if the object has a natural order that you want to implement. Such as Integer implements for numeric order, String implements for alphabetical. The second is useful if you want different orders under different circumstances.
If you write a Comparator then you need to consider where to put it. Since it has no state you could write it as a Singleton, or a static method of FriendProfile.
You can use java.lang.Comparable interface if you want to sort in only One way.
But if you want to sort in more than one way, use java.util.Compartor interface.
eg:
The class whose objects are to be Sorted on its roll_nos
public class Timet {
String name;
int roll_no;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getN() {
return roll_no;
}
public void setN(int n) {
this.roll_no = n;
}
public Timet(String name, int n) {
this.name = name;
this.roll_no = n;
}
public String toString(){
return this.getName();
}
}
The class for sorting:
public class SortClass {
public void go(){
ArrayList<Timet> arr = new ArrayList<Timet>();
arr.add(new Timet("vivek",5));
arr.add(new Timet("alexander",2));
arr.add(new Timet("catherine",15));
System.out.println("Before Sorting :"+arr);
Collections.sort(arr,new SortImp());
System.out.println("After Sorting :"+arr);
}
class SortImp implements Comparator<Timet>{
#Override
public int compare(Timet t1, Timet t2) {
return new Integer(t1.getN()).compareTo (new Integer((t2.getN())));
}
}
public static void main(String[] args){
SortClass s = new SortClass();
s.go();
}
}

Categories

Resources