Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
I used a Comparator class to define the sorting of the StringBuffer.I have implemented the Comparator class and the Comparator method compare.
Why i am getting output like this?
Code:
import java.util.Comparator;
import java.util.TreeSet;
public class SortestSetDemo {
public static void main(String[] args) {
TreeSet t1 = new TreeSet(new MyComparator());
t1.add(new StringBuffer("a"));
// t1.add("d");
t1.add(new StringBuffer("q"));
t1.add(new StringBuffer("w"));
t1.add(new StringBuffer("r"));
System.out.println(t1);
}
}
class MyComparator implements Comparator {
public int compare(Object ob1, Object ob2) {
// String i1=(String)ob1;
String i1 = ob1.toString();
// String i2=(String)ob2;
String i2 = ob2.toString(); //corrected error here instead of ob1.toString it is ob2.toString()
return -i1.compareTo(i2);
}
}
Output Shown:
[a] instead of [a,q,r,w]
You have a typo in your code. String i2 = ob1.toString(); .
This should be
String i2 = ob2.toString();
Below code is working fine -
import java.util.Comparator;
import java.util.TreeSet;
public class SortestSetDemo {
public static void main(String[] args) {
TreeSet t1 = new TreeSet(new MyComparator());
t1.add(new StringBuffer("a"));
// t1.add("d");
t1.add(new StringBuffer("q"));
t1.add(new StringBuffer("w"));
t1.add(new StringBuffer("r"));
System.out.println(t1);
}
}
class MyComparator implements Comparator {
public int compare(Object ob1, Object ob2) {
// String i1=(String)ob1;
String i1 = ob1.toString();
// String i2=(String)ob2;
String i2 = ob2.toString();
return -i1.compareTo(i2);
}
}
Output:
[w, r, q, a]
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed last year.
Improve this question
getting Exception in thread "main" java.lang.ClassCastException:
class java.lang.Integer cannot be cast to class java.lang.String
(java.lang.Integer and java.lang.String are in module java.base of
loader 'bootstrap')
at java.base/java.lang.String.compareTo(String.java:133)
at java.base/java.util.TreeMap.put(TreeMap.java:806)
at java.base/java.util.TreeMap.put(TreeMap.java:534)
at java.base/java.util.TreeSet.add(TreeSet.java:255)
at assignment3treesetdemo.addEmployee(assignment3treesetdemo.java:46)
at assignment3treesetdemo.main(assignment3treesetdemo.java:63)
import java.util.Iterator;
import java.util.TreeSet;
class Employee implements Comparable{
int empid;
String name;
float salary;
Employee(){}
Employee(int empid,String name,float salary){
this.empid=empid;
this.name=name;
this.salary=salary;
}
#Override
public int compareTo(Object o) {
Employee emp = (Employee)o;
if(salary==emp.salary)
return 0;
else if(salary>emp.salary) {
return 1;
}
else{
return -1;
}
}
}
public class assignment3treesetdemo extends Employee {
TreeSet<Object> ts = new TreeSet<>();
assignment3treesetdemo(int empid, String name, float salary) {
super(empid, name, salary);
}
public assignment3treesetdemo() {
// TODO Auto-generated constructor stub
}
boolean addEmployee(Employee emp[]) {
int i=0;
for(i=0;i<3;i++) {
ts.add(emp[i].empid);
ts.add(emp[i].name);
ts.add(emp[i].salary);}
return true;
}
void displayAllEmployees() {
Iterator itr = ts.iterator();
while(itr.hasNext()) {
System.out.println(itr.next());
}
}
public static void main(String[] args) {
assignment3treesetdemo obj = new assignment3treesetdemo();
Employee emp[] = new Employee[3];
emp[0]=new Employee(101,"Adithya",50);
emp[1]=new Employee(102,"Doshk",60);
emp[2]=new Employee(103,"Diya",90);
obj.addEmployee(emp);
obj.displayAllEmployees();
}
}
You're putting an int (boxed to Integer), a float (boxed to Float) and a String in the same TreeMap. Because you didn't specify a Comparator when you created the TreeMap, the compareTo methods of these separate objects are called. These compareTo methods are allowed to (and will) throw a ClassCastException if the object passed to it isn't of the same type. That's what you're seeing here.
As said before, you probably just want to add the employee itself. That way, the compareTo method of your Employee class will called and not the compareTo method of Integer, Float or `String.
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 4 years ago.
Improve this question
I'm trying to solve my homework. This is the code I use. Comparator for sorting a student list in 2 ways.
public class Student {
public static final Comparator<Student> BY_NAME = new ByName();
public static final Comparator<Student> BY_Gpa = new ByGpa();
private static class ByName implements Comparator<Student> {
public int compare(Student v, Student w) {
return v.getName().compareTo(w.getName());
}
}
private static class ByGpa implements Comparator<Student> {
public int compare(Student v, Student w) {
if (v.getGpa() == w.getGpa()) return 0;
else if (v.getGpa() < w.getGpa()) return -1;
else return 1;
}
}
}
I don't understand Collection.sort. Why does it have to use a complicated form like that? Why not just a static function in the class like C++ for sorting, instead of returning a class that implements Comparator which has a method compare? It's too complex.
Java 8's enhancements to the Comparator interface make it a lot more elegant:
public static final Comparator<Student> BY_NAME = Comparator.comparing(Student::getName);
public static final Comparator<Student> BY_Gpa = Comparator.comparingInt(Student::getGpa);
This question already has answers here:
Sort ArrayList of custom Objects by property
(29 answers)
Closed 5 years ago.
I have a Custom Object Suppose Team
public class Team{
String name;
int teamNo;
ArrayList<Team> innerTeams;
int teamId;
//Getters and Setter Methods
Now I want to Sort it in Ascending Order of First Property name taking into account that each Team Object has a property of itself as Team as arraylist declared as innerTeams How can I be able to Sort this. So utlimately when any arrayList of object Team is present it should be sorted.
Please anyone help me with this.
The easiest way is to have your Team class implement Comparable. You can tweak the logic inside of the compareTo to match your needs, e.g. compare inner team names, etc. Then you use Collections.sort() to do the actual sorting.
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class Team implements Comparable<Team> {
String name;
int teamNo;
List<Team> innerTeams = new ArrayList<>();
int teamId;
#Override
public int compareTo(Team o) {
if(o == null) {
return 1;
} else if(name == null) {
return 0;
} else {
return name.compareTo(o.name);
}
}
public static void main(String[] args) {
Team team1 = new Team();
team1.name = "z";
Team team2 = new Team();
team2.name = "a";
List<Team> teams = new ArrayList<>();
teams.add(team1);
teams.add(team2);
System.out.println(teams);
Collections.sort(teams);
System.out.println(teams);
}
#Override
public String toString() {
return name;
}
}
Output:
[z, a]
[a, z]
You can then also use the same approach to sort innerTeams by name if needed.
You should define Comparator of Team.
class TeamComparator implements Comparator<Team>{
public int compare(Team o1,Team o2){
return o1.name.compareTo(o2.name);
}
}
And sort by Collections.sort(teamList, new TeamComparator())
This question already has answers here:
java ArrayList contains different objects
(5 answers)
Closed 6 years ago.
I have an abstract class with several subclasses. A tester class has an ArrayList with 1 object of each subclass in it. They each have a method of the same name, how can I iterate through the ArrayList and call that method for each object?
One of my subclasses (others basically the same):
public class MyMath extends Homework {
private int pagesRead;
private String typeHomework;
public MyMath(int pagesRead, String typeHomework) {
super(pagesRead, typeHomework);
}
public void createAssignment(int p) {
setPagesRead(p);
setTypeHomework(typeHomework);
}
public void toString(int pagesRead, String typeHomework) {
System.out.println("Homework type: " + typeHomework + ". Number of pages read: " + pagesRead + ".");
}
}
In my tester class main method:
ArrayList homework = new ArrayList();
homework.add(new MyMath(5, "Math"));
homework.add(new MyScience(5, "Science"));
homework.add(new MyEnglish(5, "English"));
homework.add(new MyJava(5, "Java"));
Well, if the method is specified in your abstract class, and you have already built the ArrayList with all the objects inside it, you should simply be able to iterate through the ArrayList (for-loop) and just call the .method()
If your ArrayList is of type and your interface also has the method then you can call them like so
for(int i = 0; i < list.length();i++)
{
list[i].METHOD_NAME();
}
You can iterate through the arraylist ant it contains objects and you can call the method on that object. for example,
ArrayList<AbstractClass1> objs = new ArrayList<AbstractClass1>();
objs.add(); // you have added objects already.
Then
for(int i = 0; i< objs.size() ; i++){
objs.get(i).methodYouDefined();
}
If you haven't covered generics yet in class, you have to cast manually. If you have covered generics, you should use them! See lak91's answer.
public abstract class AbstractTest
{
public abstract void oneTwo( int i, String s );
public static void main(String[] args) {
List list = new ArrayList();
list.add( new One() );
list.add( new Two() );
for( Object test : list ) {
AbstractTest abTest = (AbstractTest) test;
abTest.oneTwo( 0, "test" );
}
}
}
class One extends AbstractTest {
#Override
public void oneTwo( int i, String s )
{
System.out.println("One");
}
}
class Two extends AbstractTest {
#Override
public void oneTwo( int i, String s )
{
System.out.println("Two");
}
}
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 5 years ago.
Improve this question
I am doing some execrices in java, I have to read words from file, then
put this words into Map type Hashmap (word<String,Integer>) . All it's done .
Next set of pair (type java.util.Map.Entry) , save into List( List<Entry<String,Integer>>) and than sort it by Collections.sort(List,Comparator) .
But it doesn't works, cause it says that the sort is not suitable and I havent so much experiences with this sort, can someone help me in this current example how to ? ... thank you for help .
There is part from code:
public static void Reader(){
class Word{
private String key;
private int value;
public int getValue(){
return value;
}
public void setValue(){
value=this.value;
}
public String getKey(){
return key;
}
public void setKey(){
key=this.key;
}
public Word(String key,Integer value){
this.key= key;
this.value = value;
}
public Word(){
}
}
Map<String, Integer> wordsmap = new HashMap<String, Integer>();
wordsmap.put("car",2); // wordsmap.put(word as key,frequency as value)
wordsmap.put("bike",6);
wordsmap.put("like",1);
List<Entry<String,Integer>> words = new ArrayList<>(wordsmap.entrySet());
Collections.sort(words,new Comparator<Word>(){
public int compare(Word o1,Word o2){
return o1.getValue() - o2.getValue();
}
});
}
public static void main(String[] args) {
Reader();
}
You sort a List<Entry<String, Integer>> with a Comparator<Entry<String, Integer>>:
Collections.sort(seznam, new Comparator<Entry<String, Integer>(){
public int compare(Entry<String, Integer> o1, Entry<String, Integer> o2){
return o1.getKey().compareTo(o2.getKey()); // for example
}
});
You haven't indicated how you want to compare the entries: I have compared keys, but you can calculate the comparison how you like.
Java 8 update, using a lambda instead of an anonymous class:
Collections.sort(seznam, (o1, o2) -> o1.getKey().compareTo(o2.getKey()));