I'm getting classcastException , can anybody solve this? [closed] - java

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.

Related

Bound mismatch error using Generics for an object array

I have used the comparable interface before but using it with generic objects and a second object has been causing me some difficulties
Here is my driver program
import java.io.*;
import java.util.*;
public class Prog2 {
public static void main (String[]args){
//Declare Variables
Scanner inFile = null;
ListArray<Part> partArray = new ListArray<Part>(13);
//Open the file
try {
inFile = new Scanner(new File("parts.txt"));
}
//If the file is not found, end the program
catch(FileNotFoundException e){
System.out.println("Error: File not found");
System.exit(0);
}
//While the file has new text, read it in
while(inFile.hasNext()){
//Read a line of code in
String temp = inFile.nextLine();
//split the line into an array
String[] tempA = temp.split(",[ ]*");
//place the specific info into variables
int pnum = Integer.parseInt(tempA[0]);
String name = tempA[1];
double price = Double.parseDouble(tempA[2]);
String warN = tempA[3];
int quant = Integer.parseInt(tempA[4]);
//add the info into an object
partArray.add(new Part(pnum, name,price,warN,quant));
}
}
}
The class meant to be written like an Array list
public class ListArray <E extends Comparable>{
//Declare Variables
private E[] list;
private int size;
//Construct Constructor
public ListArray(){
list = (E[]) new Comparable[10];
}
public ListArray(int capacity){
list = (E[]) new Comparable[capacity];
}
/*This method will allow users to get the variable stored
* at the index they specify
* #param: int index: the index of the wanted item
* #return: E: the item at the speicifed index */
public E get(int index){
return list[index];
}
/*This method will allow users to add an element to the
* end of the list array
* #param: E item: the item being added to the array */
public void add(E item){
list[size] = item;
size++;
}
/*This mehod will allow the user to find a specified item
* inside of the array
* #param: E target: the item the user wants to know the index of
* #return: int: the index of the item found */
public int find(E target){
for(int i = 0; i < size; i++){
if(target.compareTo(list[i]) == 0){
return i;
}
}
return -1;
}
/*This method will allow users to get the size of the array
* #return: int: the size of the array */
public int size(){
return size;
}
}
and the Part class that reads in from a csv file.
public class Part <E extends Comparable>{
//Declare Variables
private int pnum;
private String name;
private double price;
private String warh;
private int quant;
//Construct Constructor
public Part(){
pnum = 0;
name = "";
price = 0.0;
warh = "";
quant = 0;
}
public Part(int pnum, String name, double price, String warh, int quant){
this.pnum = pnum;
this.name = name;
this.price = price;
this.warh = warh;
this.quant = quant;
}
//Getters
public int getPnum(){
return pnum;
}
public String getName(){
return name;
}
public double getPrice(){
return price;
}
public String getWarh(){
return warh;
}
public int getQuant(){
return quant;
}
//Setters
public void setPnum(int pnum){
this.pnum = pnum;
}
public void setName(String name){
this.name = name;
}
public void setPrice(double price){
this.price = price;
}
public void setWarh(String warh){
this.warh = warh;
}
public void setQuant(int quant){
this.quant = quant;
}
When I run the program, I am given this error inside of the console
Exception in thread "main" java.lang.Error: Unresolved compilation problems:
Bound mismatch: The type Part is not a valid substitute for the bounded parameter of the type ListArray
Bound mismatch: The type Part is not a valid substitute for the bounded parameter of the type ListArray
at Prog2.main(Prog2.java:8)
From the looks of it, this is a problem of how COmparable is implemented in one of my classes, and it not being correctly implemented in the other. I tried looking at other posts on the website and tried implementing them to no avail. Thank you so much!
You have specified your ListArray to only be paramtrizable with types that extend Comparable
ListArray <E extends Comparable>
But, you're trying to parametrize it with Part, which does not extend Comparable.
It looks like you've made some mistake in making Part generic. You should have Part implement Comparable i.e. :
public class Part implements Comparable<Part>
And then implement the compareTo method in Part
#Override
public int compareTo(Part other) {
// ... code here
}
Your problem here stems from the fact that you declared the Part class of using a generic E which extends the Comparable interface.
Same goes for your ListArray class, in which you define it again as accepting a E which extends the Comparable interface.
When you try to create a new ListArray by doing so:
ListArray<Part> partArray = new ListArray<Part>(13);
it'll effectively expect something that is within bounds, in this case this being something that implements the Comparable interface. Since your Part object does not do so, this is reason why you get this error (also the compiler message is quite informative about this).
I would generally suggest you have a good read on generics if you attempt to use them, as it seems that you're lacking in understanding them.

error: incompatible type object cannot be converted to (java class) [closed]

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 5 years ago.
Improve this question
I have java class adapter and this is error (Groceries b : getData()), because object cannot be converted to Groceries.java, if i change to (Object b : getData()) i can't call a method b.getProduct().getSn() from Groceries.java
DataAdapter.java
public Groceries getBelBySN(String sn) {
Groceries pp = null;
for (Groceries b : getData()) {
if (b.getProduct().getSn().equals(sn)) {
pp = b;
break;
}
}
return pp;
}
public void updateTotal() {
long jumlah = 0;
for (Groceries b : getData()) {
jumlah = jumlah + (b.getProduct().getHarga() * b.getQuantity());
}
total = jumlah;
}
This is Groceries.java that i call on adapter
public class Groceries {
protected Product product;
protected int quantity;
public Groceries(Product product, int quantity) {
this.product = product;
this.quantity = quantity;
}
public void setProduct(Product product) {
this.product = product;
}
public Product getProduct() {
return product;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
public int getQuantity() {
return quantity;
}
It seems like getData() doesnt return a Groceries object. Could you provide the implementation for it, please.
Every object in Java inheritates from Object.class that's why you can cast to it without any problems. The Object.class doesn't have any of your Groceries functions, that's why you get an error calling them. You should probably read a good book about OOP and OOP in Java first.
EDIT:
I don't know how your getData() function looks like, but it should be something like this to make the advanced for loop work:
ArrayList<Groceries> myGroceries = new ArrayList<Groceries>();
public ArrayList<Groceries> getData(){
return myGroceries;
}
Then your loop should run just fine.
for (Groceries b : getData()) {
// Do stuff
}

ArrayList .add method missing [closed]

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 8 years ago.
Improve this question
Hello I have the following problem: I want to create an arraylist and want to add some items.
But somehow the .add Method is not there.
import java.util.ArrayList;
public class Chairing{
private int numbers;
ArrayList<Chairs>myList = new ArrayList<Chairs>();
myList.add(5,new Chairset("10"));
}
public class Chair{
int price;
String info;
public Chair(int price, Chairset c){
this.price = price;
info = c.getInfo();
}
}
public class Chairset{
String info;
public Chairset(String id){
id = info;
}
}
For some Reasons I can't add something in my new ArrayList. The constructor for Chair needs a price and an object Chairset. Chairset needs an id.
The problem is your classes have no common type, the tightest generic bound the list can have would be Object. Either use a marker interface, or notice the similarity between Chair and Chairset and have one extend the other - giving them a common type.
Also note that the line in your code where you add to the list is not in a legal location - it must be within a method.
Try this:
public class Chairing {
private int numbers;
List<Chairset> myList = new ArrayList<Chairset>();
public void someMethod() {
myList.add(5,new Chairset("10"));
}
}
public class Chair extends Chairset {
int price;
public Chair(int price, Chairset c){
super(c.getInfo());
this.price = price;
}
}
public class Chairset {
String info;
public Chairset(String id){
id = info;
}
}

Compilation error in method call [closed]

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 8 years ago.
Improve this question
class Persons {
private String name;
public Persons(String name) {
this.name = name;
}
public boolean equal(Persons p) {
return p.name.equals(this.name);
}
}
public class pa {
public static void main(String ar[]) {
Persons a = new Persons("Roman");
boolean max;
max = a.equal(new Persons());
System.out.print(max);
}
}
you do not have default constructor in your Persons class
change
max = a.equal(new Persons());
to
max = a.equal(new Persons("someValue"));
or provide default constructor
You only have 1 constructor in class Person
public Persons(String name) {
this.name = name;
}
But, you create a new instance of Person like this:
max = a.equal(new Persons());
Solutions:
Create a default constructor : public Persons () { }
Use existing constructor : max = a.equal(new Persons(""));
Always add a default constructor when providing a parametrized one.
class Persons {
private String name;
public Persons(){
}
public Persons(String name) {
this.name = name;
}
public boolean equal(Persons p) {
return p.name.equals(this.name);
}
}
You don't have a default constructor for Person,
max = a.equal(new Persons("")); // <-- need a String.
Also, you should name your method equals(), because that's the Object method;
#Override
public boolean equals(Object p) {
if (p instanceof Persons) {
return this.name.equals(((Persons) p).name);
}
return false;
}
also you do not have constructor like this :
public Persons() //no parameter
{
this.name = name;
}
so you can't create a new instance of Persons (wow! too many person.) using the above constructor.
Issue is here
Persons a = new Persons("Roman");
boolean max;
max = a.equal(new Persons()); // Persons class don't have no-argument construtor
You have to change this to
max = a.equal(new Persons("yourValue"));
Or you can add no argument constructor to Persons class.
public Persons(){
}

How can I order TreeMaps or ArrayLists holding Persons based on their ID, name, or birthdate?

I have tried almost everything and I can't seem to get my lists to order themselves.
Here's some code:
private List<Person> names = new ArrayList<Person>();
private Map<Integer, Person> peopleMap = new TreeMap <Integer, Person>();
for(int i = 0; i<20; i++)
{
Person personOne = new Person();
peopleMap.put(personOne.id,personOne);
names.add(personOne);
}
Collections.sort(names);
run();
}
My Person class:
public class Person implements Comparable {
public String name;
public int id;
public Date birthdate;
static int idRecord = 0;
The values are filled with randoms. My date has a date format.
I also have a toString method inside my person class, but for some reason when I try to print my maps it gives me the hashcode (this is the hashcode right?) Person#a62fc3.
Here is my toString inside the person clasS:
public String toString()
{
char tab = '\t';
return ("ID Number: "+id+tab+" Name: "+tab+name+tab+" Birthdate: "+(birthdate.toString()));
}
I should add that I am not able to call my toString method inside my person class. Because it is printing Person#a62fc3.
public void sortByID()
{
char tab = '\t';
for (int i = 1; i<20; i++)
System.out.println((peopleMap.get(i)).toString());
//System.out.println("ID Number: "+(peopleMap.get(i).id)+tab+" Name: "+tab+peopleMap.get(i).name+tab+" Birthdate: "+peopleMap.get(i).birthdate);
run();
}
The commented code will work but the code calling the toString does not print what it should
Compare to method inside of my Person class:
public int compareTo(Object obj) {
Person o = (Person) obj;
if (this.id == o.id) { return 0; }
if (this.id > o.id) { return 1; }
if (this.id < o.id) { return -1; }
return 0;
I can provide more code if it's needed.
Compare by name method and it's output. Should I make an arrayList to store my values in and then sort it in that?
public void sortByName()
{
// char tab = '\t';
for(int j = 1; j<20; j++)
{
// System.out.println("ID Number: "+(names.get(j).id)+tab+" Name: "+tab+peopleMap.get(j).name+tab+" Birthdate: "+peopleMap.get(i).birthdate);
//Person p = names.get(j);
System.out.println(names.get(j).toString());
}
}
Output:
Person#10b30a7
Person#1a758cb
Person#1b67f74
Person#69b332
Person#173a10f
Person#530daa
Person#a62fc3
Person#89ae9e
Person#1270b73
Person#60aeb0
Person#16caf43
Person#66848c
Person#8813f2
Person#1d58aae
Person#83cc67
Person#e09713
Person#de6f34
Person#156ee8e
Person#47b480
Thanks
Well, I can't pinpoint the exact problem, I have a few suggestions.
Maps aren't sorted.
In general, an Map is not sorted, so you will not be able to sort the keys of the map. If you want to sort the Map use the SortedMap interface.
Use Generics when possible
The Comparable interface is generic. You should probably be implementing Comparable<Person>
Then your compareTo() method should look like this:
public int compareTo(Person p) {
if (this.id > p.id) return 1;
else if (this.id < p.id) return -1;
else return 0;
}
The difference between Comparator<Person> and Comparable<Person>
You need to take a look at the Comparator interface as well as the Comparable interface.
Your Person should implement comparable in that way that you usually want a person to be sorted. Then you should write some implementations of Comparator.
public classPersonNameComparator implements Comparator<Person> {
public int compare(Person p1, Person p2) {
return p1.name.compareTo(p2.name);
}
}
The importance of using the #Override annotation
It is important to always use the #Override annotation whenever you are trying to override a method of a super class or implement an interface method. The following are a few links regarding why this is a good idea:
Overriding the java equals() method quirk
When do you use Java's #Override annotation and why?
One issue that I see is that TreeMap sorts by key not by value. Your compareTo will not be used in the sorting of the tree since it is the value in the map. Since the key in the map is the id the the items in the tree should be sorted by the id of the person.
How do you know that the map isn't sorted? Can you show us some output that shows that it is not? Are you by any chance changing the ID of the Person after it gets put into the map?
Oh, and what is names compared to personMap? Also, are the ids really contiguous starting from 1? What does this code spit out:
for (Person person : peopleMap.values()) {
System.out.println(person);
}
did you use the #Override method to make sure that you are actually overriding the toString method? It looks like it is still printing out the default toString() (ie the value of the pointer to the object).
see : comparator API.
"The ordering imposed by a Comparator c on a set of elements S is said to be consistent with equals if and only if (compare((Object)e1, (Object)e2)==0) has the same boolean value as e1.equals((Object)e2) for every e1 and e2 in S."
I don't see an equals method in your Person class. The default implementation of equals compares identity. And if you override equals, you must define hashCode two.
And this question : Consistent Equals() results, but inconsistent TreeMap.containsKey() result
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
public class Person implements Comparable<Person> {
public final String name;
public final int id;
public final Date birthdate;
public Person(int id, String name, Date birthdate) {
this.id = id;
this.name = name;
this.birthdate = birthdate;
}
public static void main(String[] args) {
List<Person> list = new ArrayList<Person>();
for (int i = 10; i > 0; i--) {
list.add(new Person(i, "name" + String.valueOf(i), new Date()));
}
System.out.println(list);
Collections.sort(list);
System.out.println(list);
}
#Override
public boolean equals(Object other) {
if (!(other instanceof Person)) {
return false;
}
return this.id == ((Person)other).id;
}
#Override
public int hashCode() {
return 41 * id;
}
#Override
public String toString() {
return "Person<" + id + ">";
}
#Override
public int compareTo(Person other) {
if (!(other instanceof Person)) {
throw new IllegalArgumentException();
}
return this.id - ((Person)other).id;
}
}
Outputs :
[Person<10>, Person<9>, Person<8>, Person<7>, Person<6>, Person<5>, Person<4>, Person<3>, Person<2>, Person<1>]
[Person<1>, Person<2>, Person<3>, Person<4>, Person<5>, Person<6>, Person<7>, Person<8>, Person<9>, Person<10>]

Categories

Resources