This question already has answers here:
Sort ArrayList of custom Objects by property
(29 answers)
How to sort Arraylist of objects
(3 answers)
Closed 9 years ago.
I m looking to sort an ArrayList which is of the type <String,int>, according to int.
So, my variable is var<String,int>
India 2
Pakistan 3
USA 1
The output becomes:
USA 1
India 2
Pakistan 3
I am confused how does it works with int. Collections.sort(var) does not works with it.
You can't use ArrayList of type
<String, int>
You can't have primitives in ArrayList as ArrayList holds objects. So, the closest you can do is to store Integer objects.
ArrayList can be of only one type if you are parameterizing it.
If you want to hold String and int, you can create a class CountryInfo with fields name and rank. Then create
ArrayList<CountryInfo> list =new ArrayList<CountryInfo>();
Then you can use
Collections.sort(list, <Comparator>)
I have created an example where you can sort your ArrayList even if its with objects. You can read through it an see if it's helps.
I have made two classes and a test class:
First class is Country:
public class Country {
private String countryName;
private int number;
public Country(String countryName, int number){
this.countryName = countryName;
this.number = number;
}
public String getCountryName(){
return countryName;
}
public void setCountryName(String newCountryName){
countryName = newCountryName;
}
public int getNumber(){
return number;
}
public void setNumber(int newNumber){
number = newNumber;
}
public String toString(){
return getCountryName() + getNumber();
}
}
Next class is Methods:
public class Methods {
private Country country;
private ArrayList<Country> overview = new ArrayList<Country>();
private ArrayList<Country> overviewSorted = new ArrayList<Country>();
int [] test;
public void regCountry(String countryname, int numbers){
if(!(countryname == "" && numbers == 0)){
overview.add(new Country(countryname, numbers));
} else {
System.out.println("The input was null");
}
}
public void showRegisteredCountries(){
if(!(overview.size() < 0)){
for(int i = 0; i < overview.size(); i++){
System.out.println("The country: " + overview.get(i).getCountryName() + " has the number: " + overview.get(i).getNumber() + " registered");
}
} else {
System.out.println("There are no country registered");
}
}
public void numbersOverFromArrayList(){
if(!(overview.size() < 0)){
test = new int [overview.size()];
for(int i = 0; i < overview.size(); i++){
test[i] = overview.get(i).getNumber();
}
}
}
public void sortArrayAndCopyItBack(){
if(!(test.length < 0)){
java.util.Arrays.sort(test);
for(int i = 0; i < test.length; i ++){
for(int j = 0; j < overview.size(); j++){
if(test[i] == overview.get(j).getNumber()){
overviewSorted.add(new Country(overview.get(j).getCountryName(), overview.get(j).getNumber()));
}
}
}
}
}
public void showTableSorted(){
if(!(overviewSorted.size() < 0)){
for(int i = 0; i < overviewSorted.size(); i++){
System.out.println("Country name: " + overviewSorted.get(i).getCountryName() + " with number: " + overviewSorted.get(i).getNumber());
}
} else {
System.out.println("There are non countrys in table that is sorted");
}
}
}
Next is the test class:
public class test2 {
public static void main(String [] args){
Methods methodes = new Methods();
for(int i = 0; i < 4; i++){
String inCountry = JOptionPane.showInputDialog("Country:");
String inNumber = JOptionPane.showInputDialog("number:");
String country = inCountry;
int number = Integer.parseInt(inNumber);
methodes.regCountry(country, number);
}
methodes.showRegisteredCountries();
methodes.numbersOverFromArrayList();
methodes.sortArrayAndCopyItBack();
methodes.showTableSorted();
}
}
My output:
The country: Norway has the number: 5 registered
The country: Sweden has the number: 2 registered
The country: Denmark has the number: 9 registered
The country: Finland has the number: 7 registered
Country name: Sweden with number: 2
Country name: Norway with number: 5
Country name: Finland with number: 7
Country name: Denmark with number: 9
That is not an ArrayList. Use TreeMap in Stead.
Map<String, Integer> countryInfo = new TreeMap<String,Integer>();
This way it will be sorted automatically
You can sort
use Collections.sort(list,Comparator implementation)
in the implementation(here I have used anonymous implementation) override compare method
where you
get last character of each string convert to string and compare them
ArrayList<String> a=new ArrayList<String>();
a.add("India 2");
a.add("Pakistan 3");
a.add("USA 1");
Collections.sort(a, new Comparator<String>() {
#Override
public int compare(String o1, String o2) {
Integer i=Integer.valueOf(o1.substring((o1.length() -1),o1.length()));
Integer j=Integer.valueOf(o2.substring((o2.length() -1),o2.length()));
return i.compareTo(j);
}
});
You can optimist code
ArrayList is a collection of one type of object. It is not like maps that can take two inputs.
Therefore, there are three options:
1. Make use of a TreeMap that contains both a Key and a Map and is automatically sorted by key or
2. Make use of an unsorted map and sort with a comparator - see Sort a Map<Key, Value> by values (Java) or
3. Use an arraylist of a custom class with a comparator.
-
1) Using a TreeMap
Treemaps are an implementation of red-black trees. See: http://docs.oracle.com/javase/1.5.0/docs/api/java/util/TreeMap.html
TreeMap<Integer,String> countries = new TreeMap<Integer,String>();
countries.put(2, "India");
countries.put(1, "USA");
countries.put(3, "Pakistan");
Iterator<Entry<Integer, String>> it = countries.entrySet().iterator();
Entry<Integer, String> entry;
while(it.hasNext())
{
entry = it.next();
System.out.println(entry.getValue() + " " + entry.getKey());
}
And this Produces:
USA 1
India 2
Pakistan 3
-
2) Make use of an unsorted map and sort with a comparator
See: Sort a Map<Key, Value> by values (Java) as the answer is very will written.
-
3) Using an ArrayList with Country Class
In order to support your example you would need to create a Country class.
You would need to do the following:
Implement Comparable within your country class and place the logic for the comparison within there.
Create a custom comparator that you will give to your Collection.sort invocation.
import java.util.ArrayList;
import java.util.Collections;
import java.util.InputMismatchException;
import java.util.Iterator;
public class CountrySortExample {
public static void main(String[] args) {
new CountrySortExample();
}
public ArrayList<Country> countries = new ArrayList<Country>();
public CountrySortExample()
{
countries.add(new Country("India",2));
countries.add(new Country("Pakistan",3));
countries.add(new Country("USA",1));
Collections.sort(countries);
Iterator<Country> it = countries.iterator();
Country count;
while(it.hasNext())
{
count = it.next();
System.out.println(count.CountryName + " " + count.CountryIndex);
}
}
class Country implements Comparable
{
public String CountryName;
public int CountryIndex;
public Country(String CountryName,int CountryIndex )
{
this.CountryName = CountryName;
this.CountryIndex = CountryIndex;
}
#Override
public int compareTo(Object o) {
if(! (o instanceof Country))
throw new InputMismatchException("Country is expected");
Country other = (Country)o;
if(other.CountryIndex > CountryIndex)
return -1;
else if(other.CountryIndex == CountryIndex)
return 0;
else return 1;
}
}
}
Further information is available at: http://www.mkyong.com/java/java-object-sorting-example-comparable-and-comparator/
If you have an object that you want to sort in more than one way, you define a Comparator class for each type of sort you want to do.
Using the example that the OP gave, here's one way to define the object and Comparators.
Here's one test result:
CountryRating [name=India, rating=2]
CountryRating [name=Pakistan, rating=3]
CountryRating [name=USA, rating=1]
CountryRating [name=USA, rating=1]
CountryRating [name=India, rating=2]
CountryRating [name=Pakistan, rating=3]
And here's the example code:
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class CountryRating {
private String name;
private int rating;
public CountryRating(String name, int rating) {
this.name = name;
this.rating = rating;
}
public String getName() {
return name;
}
public int getRating() {
return rating;
}
#Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("CountryRating [name=");
builder.append(name);
builder.append(", rating=");
builder.append(rating);
builder.append("]");
return builder.toString();
}
public static void main(String[] args) {
List<CountryRating> list = new ArrayList<CountryRating>();
CountryRating cr1 = new CountryRating("USA", 1);
CountryRating cr2 = new CountryRating("India", 2);
CountryRating cr3 = new CountryRating("Pakistan", 3);
list.add(cr1);
list.add(cr2);
list.add(cr3);
Collections.sort(list, new CountrySort());
printList(list);
System.out.println(" ");
Collections.sort(list, new RatingSort());
printList(list);
}
private static void printList(List<CountryRating> list) {
for (int i = 0; i < list.size(); i++) {
System.out.println(list.get(i));
}
}
}
class CountrySort implements Comparator<CountryRating> {
#Override
public int compare(CountryRating cr1, CountryRating cr2) {
return cr1.getName().compareTo(cr2.getName());
}
}
class RatingSort implements Comparator<CountryRating> {
#Override
public int compare(CountryRating cr1, CountryRating cr2) {
return cr1.getRating() - cr2.getRating();
}
}
Related
This question already has answers here:
How to sort an attribute of an object using Collections
(6 answers)
Closed 5 years ago.
I have a Array list of object for class "Emp"[String eno, skill; ArrayList<Jobs> Empjobs;].
EmpJobs in itself is an arraylist for class "Jobs"[String jobId, skill;int priority, TTC;].
Now in code I created few object of Emps, say Emp1, Emp2 and they have 2 jobs assigned to each as objects of Jobs class.
job11,job12 assigned to Emp1
job21, job22 assigned to Emp2
I need to sort Arraylist of Emp based on total of their jobs TTC(Time to Completeion). I tried using comparor method but no succeess. Any help will be much appreciated.below are snippets of code.
Also to add,
Emp array values are like : 'EmpId#Skill'
Job Array values are like : 'skill#priority#TTC#JobId'
I am not able to work out Collections.sort(emp2,new MyComparator());
class EmpJobsAssign{
class Emp
{
String eno, skill;
ArrayList<Jobs> Empjobs;
public Emp(){
}
#Override
public String toString() {
return ("eno:"+this.eno+
" skill: "+ this.skill+
" Job: "+ this.Empjobs);
}
}
public class MyComparator implements Comparator<Emp> {
#Override
public int compare(Emp e1, Emp e2) {
if (e1.Empjobs.TTC > e2.Empjobs.TTC)
{
return 1;
}
else if (e1.Empjobs.TTC > e2.Empjobs.TTC)
{
return -1;
}
return 0;
}
}
class Jobs
{
String jobId, skill;
int priority, TTC;
public Jobs(){
}
#Override
public String toString() {
return ("jobId:"+this.jobId+
" skill: "+ this.skill +
" priority: "+ this.priority +
" TTC: "+ this.TTC);
}
}
public static void main(String []args){
String[] arrayEmp = {"w4#j","w1#c","w2#c","W3#j"};
String[] arrayJob = {"c#3#25#obj1","j#2#20#obj2","j#1#45#obj3","c#4#45#obj4","c#1#15#obj5"};
EmpJobsAssign HW =new EmpJobsAssign();
EmpJobsAssign.Emp emp=HW.new Emp();
EmpJobsAssign.Jobs job=HW.new Jobs();
Emp[] emps= HW.SortEmp(arrayEmp,0);
Jobs[] empjobs=HW.SortJob(arrayJob,1,2);
int jobindex=0;
while(jobindex < empjobs.length)
{
job=empjobs[jobindex];
ArrayList<Emp> emp2=new ArrayList<Emp>();
String AssignedFlag="";
for(int empindex=0;empindex<emps.length;empindex++)
{
AssignedFlag="F";
emp=emps[empindex];
if(emp.Empjobs == null) {emp.Empjobs=new ArrayList<Jobs>();}
if(emp.skill.equals(job.skill) && emp.Empjobs.isEmpty()){
emp.Empjobs.add(job);
System.out.println("empjobs : " +emp);
AssignedFlag="T";
System.out.println("Emp2 "+ emp2.size());
break;
}
}
System.out.println(" AssignedFlag "+AssignedFlag);
if(AssignedFlag.equals("F")) {
Collections.sort(emp2,new MyComparator());
System.out.println("Inside If "+ emp2.get(0));
Iterator itr=emp2.iterator();
while(itr.hasNext()){
System.out.println("test "+ itr.next());
}
}
jobindex++;
}
System.out.println("check");
System.out.println(Arrays.toString(emps));
System.out.println(Arrays.toString(empjobs));
}
private Emp[] SortEmp(String[] a, int index1)
{
Emp[] SortEmp=new Emp[a.length];
for(int i=0;i<a.length;i++){
for(int j=i+1;j<a.length;j++){
if(Integer.parseInt(a[i].substring(1,2))>Integer.parseInt(a[j].substring(1,2))){
String temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
Emp tempEmp = new Emp();
tempEmp.eno=a[i].split("#")[0];
tempEmp.skill=a[i].split("#")[1];
SortEmp[i]=tempEmp;
}
return SortEmp;
}
private Jobs[] SortJob(String[] a, int index1, int index2)
{
Jobs[] SortJobs=new Jobs[a.length];
for(int i=0;i<a.length;i++){
for(int j=i+1;j<a.length;j++){
if(Integer.parseInt(a[i].split("#")[index1])>Integer.parseInt(a[j].split("#")[index1])){
String temp=a[i];
a[i]=a[j];
a[j]=temp;
}
if(Integer.parseInt(a[i].split("#")[index1])==Integer.parseInt(a[j].split("#")[index1])){
if(Integer.parseInt(a[i].split("#")[index2]) > Integer.parseInt(a[j].split("#")[index2])){
String temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
}
Jobs tempJobs=new Jobs();
tempJobs.jobId=a[i].split("#")[3];
tempJobs.skill=a[i].split("#")[0];
tempJobs.priority=Integer.parseInt(a[i].split("#")[1]);
tempJobs.TTC=Integer.parseInt(a[i].split("#")[2]);
SortJobs[i]=tempJobs;
}
return SortJobs;
}
}
Don't put down your own comparison if you don't have to.
Your compare() boils down to:
return Integer.compare(e1.Empjobs.TTC, e2.Empjobs.TTC);
Completely eliminating the chance of introducing such subtle typos as your original code is showing (where you simply did a < b, a b).
The comparator is incorrectly implemented, both if statements have the same predicate.
#Override
public int compare(Emp e1, Emp e2) {
if (e1.Empjobs.TTC > e2.Empjobs.TTC) // predicate 1
{
return 1;
}
else if (e1.Empjobs.TTC > e2.Empjobs.TTC) // predicate 2, same as predicate 1
{
return -1;
}
return 0;
}
Change the second predicate to e1.Empjobs.TTC < e2.Empjobs.TTC.
I have following data in string(comma format) (Name,Mark)
A,20,B,10,C,30
I want to convert into Descending order like :
C,30,A,29,B,10
Please help me how can i implement in android ?
Here is code what i have prepared....
public class custom_sort {
public String name;
public int mark;
public custom_sort(String a, int b) {
// TODO Auto-generated constructor stub
name = a;
mark = b;
}
void setname(String s)
{
name=s;
}
void setmark(int s)
{
mark = s;
}
String getname()
{
return(name);
}
int getmark()
{
return(mark);
}
}
Thanks in Advance,
There are many ways of doing this. I see that you have already made a class: custom_sort. We can use this to sort it, if we just make it comparable. We do this by implementing the Comparable interface.
public class custom_sort implements Comparable{
Then all you need to do is implement the one required method:
#Override
public int compareTo(custom_sort cs) {
/*
This method should return 0 if the two objects are equal,
1 if this is biggest
and -1 if cs is biggest */
}
Then you can put all the custom_sorts in an List and just do Arrays.sort(yourArray).
You could also check out this post Android sort array
Use ArrayList rather than array of string.
This might not be the best solution but it works.
Initialize the ArrayList
ArrayList<String> names = new ArrayList<>();
ArrayList<Integer> scores = new ArrayList<>();
Fill data inside the ArrayList
names.add("A");
scores.add(20);
....
Now sort them
private void sortScoreAndName() {
for (int i = 0; i < scores.size(); i++) {
for (int j = 0; j < i; j++) {
if (scores.get(i) > scores.get(j))
swap(i, j);
}
}
}
private void swap(int i, int j) {
int tempSco = scores.get(i);
String tempName = names.get(i);
scores.remove(i);
names.remove(i);
scores.add(i, scores.get(j));
names.add(i, names.get(j));
scores.remove(j);
names.remove(j);
scores.add(j, tempSco);
names.add(j, tempName);
}
Now your ArrayList is in descending order. You can get the corresponding data using.
names.get(poition);
scores.get(position);
try this:
import android.support.v4.util.Pair;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
String[] values = {"A", "20", "B", "10", "C", "30"};
List<Pair> pairs = new ArrayList<>();
for (int i = 0; i < values.length; i += 2) {
pairs.add(new Pair<>(values[i], Integer.parseInt(values[i + 1])));
}
Collections.sort(pairs, new Comparator<Pair>() {
#Override
public int compare(Pair lhs, Pair rhs) {
return ((Integer) rhs.second).compareTo((Integer) lhs.second);
}
});
The List pairs is now sorted like you wish. Check out the Pair class i used http://developer.android.com/reference/android/util/Pair.html
And if you want to convert it back following code will help you:
String[] newValues = new String[values.length];
int i = 0;
for (Pair pair : pairs) {
newValues[i] = (String) pair.first;
newValues[i + 1] = Integer.toString((Integer) pair.second);
i += 2;
}
I'm a beginner when it comes to Java and I'm trying to pull these values vertically and store them in a data type with their reference. So "A" would have 1,8,7,6 mapped to it and the dates in front would be excluded as well. The csv file is below.
10/1/14, A,B,C,D,E,F,G,H
10/2/14, 1,2,3,4,5,6,7,8
10/3/14, 8,1,2,3,4,5,6,7
10/4/14, 7,8,1,2,3,4,5,6
10/5/14, 6,7,8,1,2,3,4,5
Here is my code. So far I've been able to grab the rows individually, but I'm I don't know how to add them to a data structure. This would return >> C3218
class Main {
public static void main(String[] args) {
Read r = new Read();
r.openFile();
r.readFile();
r.closeFile();
}
}
import java.io.*;
import java.util.*;
public class Read {
private Scanner x;
public void openFile() {
try {
x = new Scanner(new File("test.csv"));
}
catch(Exception e){
System.out.println("could not find file");
}
}
public void readFile() {
while(x.hasNext()){
String a = x.next();
String[] values = a.split(",");
System.out.printf(values[3]); // gets line
}
}
public void closeFile() {
x.close();
}
}
Java is an Object Oriented programming language. I'm going to assume that what you call "data structures" are Objects in Java parlance. For example (and these are just examples, not something you specifically could use for your situation), if I want to represent a person, I might have something like this
public interface Person{
String getName();
Date getBirthDate();
}
public class GenericPerson implements Person{
private final String name;
private final Date bdate;
public GenericPerson(String fullName, Date birthdate){
name = fullName;
bdate = birthdate;
}
#Override
public String getName() {
return name;
}
#Override
public Date getBirthDate() {
return bdate;
}
}
Pretty sparse, but I'm just trying to show some basic concepts.
You asked
I don't know how to add them to a data structure.
In my example, you would instantiate a GenericPerson
Person p = new GenericPerson(name,date);
Of course, you'll need the name and date variables. That's where the parsing the file comes in. So if I had a file of the form
George Costanza,5/4/1956
Cosmo Kramer,12/12/1960
Jerry Seinfeld,1/2/1959
Then in my code to parse the file I might have
String line = scanner.next();
String[] values = line.split(",");
Person p = new GenericPerson(values[0],getDateFormatter().parse(values[1]));
So you create your Object type, defining what fields you want it to have. And then populate them via a constructor or setter methods. An example of setter methods would be if I modified the GenericPerson like this
public class GenericPerson implements Person{
private String name;
private Date bdate;
public void setName(String n){
name = n;
}
public void setBirthDate(Date d){
bdate = d;
}
#Override
public String getName() {
return name;
}
#Override
public Date getBirthDate() {
return bdate;
}
}
Now I would need to call those to set the values in the Object.
For your case, you'll need to define some Object type that the data is meant to define. The type will have fields like the GenericPerson and you need to have setter methods or a constructor that takes arguments corresponding to the fields.
I highly recommend following the online tutorial for java beginners.
It took me 30 minutes just to get your code to compile and run correctly.
I used a List of a Column class that I created. The Column class contains the name of the column and the values in that CSV column.
The test.csv file is in the same directory as the Java class.
Here's the results.
A: 1, 8, 7, 6
B: 2, 1, 8, 7
C: 3, 2, 1, 8
D: 4, 3, 2, 1
E: 5, 4, 3, 2
F: 6, 5, 4, 3
G: 7, 6, 5, 4
H: 8, 7, 6, 5
And here's the code.
package com.ggl.testing;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class CSVColumns implements Runnable {
public static void main(String[] args) {
new CSVColumns().run();
}
#Override
public void run() {
Scanner scanner = openFile();
if (scanner != null) {
readFile(scanner);
closeFile(scanner);
}
}
private Scanner openFile() {
String fileString = "test.csv";
return new Scanner(getClass().getResourceAsStream(fileString));
}
private void readFile(Scanner scanner) {
List<Column> columnList = new ArrayList<>();
String a = scanner.nextLine();
a = a.replace(" ", "");
String[] values = a.split(",");
for (int i = 1; i < values.length; i++) {
Column column = new Column(values[i]);
columnList.add(column);
}
while (scanner.hasNext()) {
a = scanner.nextLine();
a = a.replace(" ", "");
values = a.split(",");
for (int i = 0; i < columnList.size(); i++) {
Column column = columnList.get(i);
column.addValue(Integer.valueOf(values[i + 1]));
}
}
for (int i = 0; i < columnList.size(); i++) {
System.out.println(columnList.get(i));
}
}
private void closeFile(Scanner scanner) {
scanner.close();
}
public class Column {
private List<Integer> values;
private final String name;
public Column(String name) {
this.name = name;
this.values = new ArrayList<>();
}
public List<Integer> getValues() {
return values;
}
public void addValue(int value) {
this.values.add(Integer.valueOf(value));
}
public String getName() {
return name;
}
#Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append(name);
builder.append(": ");
for (int i = 0; i < values.size(); i++) {
int value = values.get(i);
builder.append(value);
if (i < (values.size() - 1)) {
builder.append(", ");
}
}
return builder.toString();
}
}
}
Using LinkedHashMap to store header(as Keys). LinkedHashMap preserves the insertion-order:
public void readFile() {
Map<String, String> map = new LinkedHashMap<String, String>();
boolean setInitValues = true, setKeys = true;
String[] keys = null;
while (x.hasNext()) {
String a = x.nextLine();
String[] values = a.split(",");
if (setKeys) { // set keys
keys = Arrays.copyOfRange(values, 1, values.length);
setKeys = false;
} else {
if (setInitValues) { // set initial values
for (int i = 1; i < values.length; i++)
map.put(keys[i - 1], values[i].trim());
setInitValues = false;
} else
// continue appending values
for (int i = 1; i < values.length; i++)
map.put(keys[i - 1],
map.get(keys[i - 1]).concat(values[i].trim()));
}
}
printMap(map); // print what you got
}
void printMap(Map<String, String> map) {
for (Map.Entry<String, String> entry : map.entrySet())
System.out.println("Key : " + entry.getKey() + " Value : "
+ entry.getValue());
}
Output :
Key : A Value : 1876
Key : B Value : 2187
Key : C Value : 3218
Key : D Value : 4321
Key : E Value : 5432
Key : F Value : 6543
Key : G Value : 7654
Key : H Value : 8765
I want to display a list of orders of type ArrayQueue <Order>
The class Order has an ArrayStack<String> as one of its attributes. I overrode the toString() method in the class Order, but how do I override it in the ArrayStack class? Because this is the output I get when I display:
OrderNumber Name Date ArrayStack#481adc30
What would I have to do to display the Strings in ArrayStack correctly? Do I make changes to class ArrayStack or change something in my Display method?
This is my Display method:
public void display(){
if (!isEmpty())
for (int i = 0; i < numberOfEntries; i++) {
System.out.println(queue[(frontIndex + i) % queue.length]);
}
else System.out.println("You don't have any orders");
}
ArrayStack Class:
public class ArrayStack < T > implements StackInterface < T >
{
private T [] stack; // array of stack entries
private int topIndex; // index of top entry
private static final int DEFAULT_INITIAL_CAPACITY = 50;
public ArrayStack ()
{
this (DEFAULT_INITIAL_CAPACITY);
} // end default constructor
public ArrayStack (int initialCapacity)
{
// the cast is safe because the new array contains null entries
# SuppressWarnings ("unchecked")
T [] tempStack = (T []) new Object [initialCapacity];
stack = tempStack;
topIndex = -1;
} // end constructor
/* Implementations of the stack operations */
Order Class:
import java.util.Date;
public class Order {
int orderNumber;
String customerName;
Date date;
StackInterface <String> items;
Order( int number, String name, Date datum, StackInterface<String> item){
orderNumber = number;
customerName= name;
date= datum;
items = item;
}
/Overriding toString() to Display a list of Orders as one String line.
public String toString(){
return orderNumber + " " + customerName + " " + date + " " + items;
}
You can override toString() method in ArrayStack as shown here. This will solve your problem.
public String toString() {
String result = "";
for (int scan = 0; scan < top; scan++)
result = result + stack[scan].toString() + "\n";
return result;
}
May be you should do this:
System.out.println(Arrays.toString(queue.toArray()));
Use this:
System.out.println(Arrays.toString(queue));
I am using an ArrayList with book titles and book ratings. How can I change this code to make the bubble sort for alphabetical instead of numeric?
System.out.println("\r" + "In order by rating");
for (int out = 0; out < bookList.size(); out++) {
for (int in = 0; in < bookList.size() - 1; in++)
if (bookList.get(in).getRating() < bookList.get(in + 1).getRating()) {
Book temp = bookList.get(in);
bookList.set(in, bookList.get(in+1));
bookList.set(in+1, temp);
}
System.out.println(videoList.get(out).getTitle() + " " + videoList.get(out).getRating());
}
}
My other classes are below.
Book
public class Book {
String title;
int rating;
public Book(String pTitle, int pRating) {
title = pTitle;
rating = pRating;
}
public String getTitle() {
return title;
}
public int getRating() {
return rating;
}
public void setTitle(String newTitle) {
title = newTitle;
}
public void setRating(int newRating) {
rating = newRating;
}
}
Library
import java.util.ArrayList;
public class Library {
public static void main (String [] args) {
ArrayList<Book> bookList = new ArrayList<Book>();
Book b1 = new Book ("Huckleberry Finn", 5);
Book b2 = new Book ("The Great Gadsby", 2);
Book b3 = new Book ("Harry Potter", 3);
Book b4 = new Book ("Animal Farm", 4);
Book b5 = new Book ("The Mist", 1);
bookList.add(b1);
bookList.add(b2);
bookList.add(b3);
bookList.add(b4);
bookList.add(b5);
System.out.println("Original sequence");
for (int cnt = 0; cnt < videoList.size(); cnt++) {
System.out.println(bookList.get(cnt).getTitle() + " " + bookList.get(cnt).getRating());
}
}
}
Is there a way to alter the code in the algorithm class to display the bookList sorted by Title?
You can't use < directly on two Strings, but you can use compareTo.
if (bookList.get(in).getTitle().compareTo(bookList.get(in + 1).getTitle()) < 0) { ...
If s1 and s2 are strings, s1.compareTo(s2) returns a negative value if s1 is lexicographically less than s2, a positive value if s1 is greater, and 0 if the two strings are equal.
For your class Book make it implement Comparable. You'll have to create some methods in your Book class in order to compile. Implement them according to the Java API then you can just throw them into a TreeSet<Book> and it will be sorted.
Edit:
I realize this doesn't directly answer your question, but it would be a more Java solution.
I think change your code :
if (bookList.get(in).getRating() < bookList.get(in + 1).getRating())
to
if (bookList.get(in).getTitle().compareTo(bookList.get(in + 1).getTitle()<0)
would be OK.
But,why dont you implement different Comparators and use it like this: Collections.sort(bookList,yourComparator)
something like this:
public static void main(String[] args) {
List<Book> bookList = new ArrayList<Book>();
Collections.sort(bookList, new TitleComparator());
Collections.sort(bookList, new RatingComparator());
}
static class TitleComparator implements Comparator<Book> {
#Override
public int compare(Book o1, Book o2) {
return o1.getTitle().compareTo(o2.getTitle());
}
}
static class RatingComparator implements Comparator<Book> {
#Override
public int compare(Book o1, Book o2) {
return o1.getRating() - o2.getRating();
}
}
To implement bubble-sort for any type of Object, in that case Book, implements in your object class the interface Comparable and override the methode compareTo to define your desired handling.
The method should return a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object.
As stated in the javadoc :
http://docs.oracle.com/javase/7/docs/api/java/lang/Comparable.html
In your case, the compareto method is already implemented in the String class so you can directly use it on the book's title.
Your validation would then look like this :
if (bookList.get(in).getTitle().compareTo(bookList.get(in + 1).getTitle()) < 0)