java.lang.Object cannot be converted to the class i created [duplicate] - java

This question already has answers here:
What are Generics in Java? [closed]
(3 answers)
Closed 3 years ago.
im having a problem calling a method i created for a class when it is returned from a list. I get a "java.lang.Object cannot be converted to Thing"
error when running the following code
public class Test1
{
public static void main(String args[])
{
Thing whipersnaper = new Thing(30, "whipersnaper");
List storage = new List();
storage.insert(whipersnaper);
Thing x = storage.getItem(0);
x.doubleWeight();
System.out.println(x.getWeight());
}
}
here is the "Thing" class
public class Thing
{
private int weight;
private String name;
public Thing(int weight,String name){
this.weight = weight;
this.name = name;
}
public void doubleWeight(){
this.weight *= 2;
}
public int getWeight(){
return this.weight;
}
}
finally here is the List class
public class List
{
private Object[] itemList;
private int size;
public List()
{
this.itemList = new Object[10];
this.size = 0;
}
public void insert(Object item){
itemList[size] = item;
size++;
}
public Object getItem(int index){
return itemList[index];
}
}
i need the list to be able to hold objects of any type and not exclusively Thing objects.
i have tried to google a solution but I cant find a good way to phrase the question to get an answer. thanks in advance.

Change that line Thing x = storage.getItem(0); with Thing x = (Thing) storage.getItem(0);

Thing x = (Thing) storage.getItem(0);

Related

java.lang.nullpointer error in linkedlist in android [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
I am trying to make a student registration interface with several classes, provided in the requirement. In doing so, the linkedlist in my CourseFactory class is showing a null pointer.
public class Course {
private String id;
private String title;
private int credit;
private int tuitionPerCredit;
public void setId(String id){
this.id=id;
}
public String getId(){
return this.id;
}
public void setTitle(String title){
this.title=title;
}
public String getTitle(){
return this.title;
}
public void setCredit(int credit){
this.credit=credit;
}
public int getCredit(){
return this.credit;
}
public void setTuitionPerCredit(int tuitionPerCredit){
this.tuitionPerCredit=tuitionPerCredit;
}
public int getTuitionPerCredit(){
return tuitionPerCredit;
}
public int getSubTotal(){
return this.credit*this.tuitionPerCredit;
}
}
And CourseFactory class
import java.util.LinkedList;
import static android.R.attr.id;
public class CourseFactory {
LinkedList<Course> cList;
public void CourseFactory(){
Course course = new Course();
course.setId("CSE327");
course.setTitle("SOFT ENG");
course.setCredit(3);
course.setTuitionPerCredit(1500);
cList.add(course);
Course course1 = new Course();
course1.setId("CSE115");
course1.setTitle("INTRO C");
course1.setCredit(3);
course1.setTuitionPerCredit(1500);
cList.add(course1);
Course course2 = new Course();
course2.setId("CSE215");
course2.setTitle("INTRO JAVA");
course2.setCredit(3);
course2.setTuitionPerCredit(1500);
cList.add(course2);
Course course3 = new Course();
course3.setId("CSE225");
course3.setTitle("DATA STRUCT");
course3.setCredit(3);
course3.setTuitionPerCredit(1500);
cList.add(course3);
Course course4 = new Course();
course4.setId("CSE373");
course4.setTitle("ALGOR.");
course4.setCredit(3);
course4.setTuitionPerCredit(1500);
cList.add(course4);
}
public Course getCourse(String id){
int temp = 0;
for(int i=0;i<cList.size();i++) {
if (cList.get(i).getId().equals(id)) {
temp=i;
break;
}
}
return cList.get(temp);
}
}
The error is on the line "if (cList.get(i).getId().equals(id))
You have to initialize LinkedList. Or else it will get null-pointer exception.
LinkedList<Course> cList=new LinkedList<Course>();
You need to initialize cList before use
LinkedList<Course> cList=new LinkedList<Course>();
or better, initialize into CourseFactory's constructor
public void CourseFactory(){
cList=new LinkedList<Course>();
Course course = new Course();
...
...
}
diamond operator is supported in -source 7 or higher
LinkedList<Course> cList=new LinkedList<>();

Java toString() not printing the correct variable [duplicate]

This question already has answers here:
Why does my ArrayList contain N copies of the last item added to the list?
(5 answers)
Closed 7 years ago.
I have a class like this in Java:
public class Wrapper {
public static List<Type> list;
#Override
public String toString() {
return "List: " + this.list;
}
public static void main(String[] args) {
Wrapper w = new Wrapper();
System.out.println(w);
}
}
and a class like this:
public class Type {
private static String name;
public Type(String n) {
this.name = n;
}
#Override
public String toString() {
return this.name;
}
}
Instead of getting the name of each item, I get the name of the last item for each item in the array. Any suggestions?
in your Type class you are marking your name as static so when printing type.toString() you always have only one value.
And if you want to print all member of your list, use:
for(Type t : list){
System.out.print(t.toString());
}
#Override
public String toString() {
String s = "";
for(Type t : list) {
s += t;
}
return s;
}

Blue J - identifier expected message? [duplicate]

This question already has answers here:
Java Reserve Keywords
(4 answers)
Closed 7 years ago.
i'm writing the following code and i'm getting the error 'identifier expected' on the line
private String class;
public class Records
{
private String name;
private String class;
private int cabinNumber;
public Records(String n, String c, int cn)
{
name = n;
class = c;
cabinNumber = cn;
}
public void setClass (String c){
class = c;
}
public void set cabinNumber (int cn){
cabinNumber = cn;
}
public String name(){
return name;
}
public String class(){
return class;
}
public int cabinNumber(){
return cabinNumber;
}
}
can someone please explain why this is happening and what I can do to fix it?
thank you!
class is a java keyword, you cannot have a variable with this name.

Create a List of generic list

How do I create a list of generic list? I have a Boxcar class that takes a generic argument and a Train class that is supposed to create a list of Boxcars. We are supposed to specify the type that will be in Boxcar in a separate main class, so until then boxcar has to stay generic. The following is the code that I have written. It compiles but in a separate driver class when calling the load method I get the error The method load(capture#1-of ?) in the type Boxcar<capture#1-of ?> is not applicable for the arguments (Person)
package proj5;
import java.util.ArrayList;
import java.util.List;
public class Train {
private List<Boxcar<?>> train;
private int maxSpeed;
private int minSpeed;
private String position;
private int numBoxcars;
private int maxNumBoxcars;
private int speed;
private String destination;
private boolean stopped = true;
public Train(int maxSpeed, int minSpeed, int maxNumBoxcars, String position){
train = new ArrayList<Boxcar<?>>();
this.maxSpeed = maxSpeed;
this.minSpeed = minSpeed;
this.maxNumBoxcars = maxNumBoxcars;
this.position = position;
}
public int getMaxNumBoxcars(){
return maxNumBoxcars;
}
public int getSpeed(){
return speed;
}
public String getPosition(){
return position;
}
public int getMaxSpeed(){
return maxSpeed;
}
public int getNumBoxcars(){
return numBoxcars;
}
public List<Boxcar<?>> getTrain(){
return train;
}
public void depart(String destination){
this.destination = destination;
speed = minSpeed;
stopped = false;
}
public void arrive(){
stopped = true;
position = destination;
}
public void addCar(Boxcar<?> boxcar, int i){
if(stopped){
boxcar.setMaxItems(i);
train.add(boxcar);
}
}
public void removeCar(int i){
if(stopped){
train.remove(i);
}
}
}
package proj5;
import java.util.ArrayList;
import java.util.List;
import java.util.Collections;
public class Boxcar<T extends Comparable<T>> {
private List<T> boxcar;
private int maxItems;
public Boxcar(){
boxcar = new ArrayList<T>();
}
public void load(T thing){
if(!boxcar.contains(thing) && boxcar.size() < maxItems){
boxcar.add(thing);
Collections.sort(boxcar);
}else{
}
}
public int getMaxItems(){
return maxItems;
}
public void setMaxItems(int i){
maxItems = i;
}
public void unload(T thing){
boxcar.remove(thing);
}
public List<T> getBoxcar(){
return boxcar;
}
}
I hope this better conveys what I am trying to accomplish
BoxCar which is a generic class:
class BoxCar<T>{
}
Train class which has a list of Boxcar:
class Train {
List<BoxCar<PassTheTypeHere>> = new ArrayList<BoxCar<PassTheTypeHere>>();
}
You need to supply a type in place of T and ? when creating a Generic List. For example a List of Boxcars containing Strings would look like this:
List<Boxcar<String>> train = new ArrayList<Boxcar<String>>();
The ? is an example of a wildcard, while a T represents a type that is referenced inside the source of List. That point can be tricky to understand without a deeper understanding of Generics, but I wanted to be sure address it for completeness sake. Take a look at this page for more information about how to use Generics inside your code.
Looking at your revised question, I would direct you to this line of code:
public class Boxcar<T extends Comparable<T>> {
and then just below it this line:
private List<T> boxcar;
This means whatever type you pass to new Boxcar<type>() will be carried over to the inner list (and other methods that expect an object of type T).
Based on the wording of your original question it sounds like you want to create a list of boxcars.
Below is all you would need to do.
private List<Boxcar> boxcarList = new ArrayList<Boxcar>();

java.lang.NullPointerException error how to fix? [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 7 years ago.
having problem with null pointer exception and i read few article bout that error and still coundnt figure out what the problem.
The error happen at CompatibleActivity[topIndex]=new Activity(aNum,bNum,c);
topIndex=0 by the way.
Can anyone highlight the problem im having?
here my class
public class Schedulingtest {
public static void main (String[] args) throws IOException
{
Scanner fileScan;
fileScan=new Scanner(new File("data.txt"));
Schedule compatibility = new Schedule();
while(fileScan.hasNext())
{String url=fileScan.nextLine();
compatibility.addActivity(url);
}
}
public class Schedule{
import java.util.Scanner;
import java.util.Arrays;
public class Schedule {
Activity[] CompatibleActivity;
int totalTime=0,topIndex=0;
Scanner urlScan;
public Schedule(){
Activity[] CompatibleActivity=new Activity[30];
}
public int getTotalTime()
{return totalTime;
}
public void addActivity(String entry){
urlScan=new Scanner(entry);
urlScan.useDelimiter(" ");
String c=null;
int aNum = 0,bNum=0;
while(urlScan.hasNext())
{String a=urlScan.next();
String b=urlScan.next();
c=urlScan.next();
aNum=Integer.parseInt(a);
bNum=Integer.parseInt(b);
}
CompatibleActivity[topIndex]=new Activity(aNum,bNum,c);
topIndex++;
System.out.println("Activity added: start "+aNum+ " stop "+bNum+" "+c );
}
}
Activity Class
public class Activity {
private int start,stop,duration;
private String name;
public Activity(int Start,int Stop,String Name)
{
start=Start;
stop=Stop;
name=Name;
duration=Stop-Start;
}
public String getName()
{return name;
}
public int getStart()
{return start;
}
public int getStop()
{return stop;
}
public int getDuration()
{return duration;
}
public boolean compatible(int Start1,int Stop1,int toMatchsideStart,int toMatchsideStop)
{
int Start=Start1;
int Stop=Stop1;
int toMatchStart=toMatchsideStart;
int toMatchStop=toMatchsideStop;
if(toMatchStop<=Start)
{return true;
}
if(toMatchsideStart>=Stop)
{return true;
}
else
{return false;}
}
public String toString()
{return( name+"<"+start+","+stop+">"); }
}
Most likely you have CompatibleActivity declared in your class as
private Activity[] CompatibleActivity;
which declares a reference and initializes it to null by default. You need to assign it a real array with enough elements (e.g. in your constructor):
CompatibleActivity = new Activity[myBigNumber];
If the NullPointerException is definitely on that line, then it can only be caused by CompatibleActivity being null. You will need to find in your code where that Array Object is declared and make sure that it is also instantiated, e.g.
Activity[] CompatibleActivity = new Activity[size];
Check if you've initialized the array before you access one of its cells. You need an expression like
CompatibilityActivity = new Activity[1]; // or any other positve number if size is bigger
Activity[] CompatibleActivity = new Activity[size];
// put some element in it like
CompatibleActivity[0]=new CompatibleActivity();

Categories

Resources