Convert ArrayList to Array throws java.lang.ArrayStoreException - java

i have a method convertToArray() which converts an ArrayList to an array. I want to call this method every time an element is added to the ArrayList.
public class Table extends ArrayList<Row>
{
public String appArray[]; //Array of single applicant details
public String tableArray[][]; //Array of every applicant
/**
* Constructor for objects of class Table
*/
public Table()
{
}
public void addApplicant(Row app)
{
add(app);
convertToArray();
}
public void convertToArray()
{
int x = size();
appArray=toArray(new String[x]);
}
}
When i call the addApplication(Row app) method I get the error: java.lang.ArrayStoreException
So I changed my addApplicant() method to:
public void addApplicant(Row app)
{
add(app);
if (size() != 0)
convertToArray();
}
I get the same error message. Any ideas why? I figured if it checks the ArrayList has elements before converting it the error should not be thrown?
I can provide the full error if needed

ArrayStoreException thrown to indicate that an attempt has been made to store the wrong type of object into an array of objects.
So,
public Row[] appArray; // Row - because you extend ArrayList<Row>
public void convertToArray()
{
int x = size();
appArray = toArray(new Row[x]);
}

Related

Why we can use methods of ArrayList without creating new ArrayList object?

We have to create a object of any class to use their funtionalities unless those are static functionalities. But why we dont need to create a ArrayList object to use its methods like add, contains etc..
ArrayList<Egg> myList = new ArrayList<Egg>();
myList.add(a);
According to my understanding, myList is just variable which holds ArrayList object's reference of type ArrayList class. So again how can we write following without passing object to myList.
ArrayList<Egg> myList;
myList.add(a);
Complete code:
import java.util.ArrayList;
public class DotCom {
private ArrayList<String> locationCells;
public void setLocationCells(ArrayList<String> loc)
{
locationCells = loc;
}
public String checkYourself(String userInput)
{
String result = "miss";
int index = locationCells.indexOf(userInput);
if (index >= 0) {
locationCells.remove(index);
if (locationCells.isEmpty()) {
result = "kill";
}
else
{
result = "hit";
}
}
return result;
}
//TODO: all the following code was added and should have been included in the book
private String name;
public void setName(String string) {
name = string;
}
}
PS
I am referring heads first java book.
The ArrayList reference is being set in the setter method:
public void setLocationCells(ArrayList<String> loc)
{
locationCells = loc;
}
If this method is not called, and the reference not set before trying to use the ArrayList, then the code will throw a NullPointerException.
Side note: This does not look to be safe code, since it can be easily run incorrectly and so a NPE is easy to create. Better perhaps to set the ArrayList (List is even better) in a constructor.

Tester class doesn't think my ArrayList is an ArrayList

I'm trying to create an ArrayList of type Item in my Store class and then test it in another class called StoreTester. I keep getting the error: The method get() is undefined for the type Store. So Java thinks my tester object of type Store is not an ArrayList even though I tried to make it so.
My Store class constructor:
import java.util.ArrayList;
public class Store
{
private ArrayList<Item> blockbuster;
public Store(){
blockbuster = new ArrayList<Item>();
}
public void addItem(Item i){
blockbuster.add(i);
}
}
This is my StoreTester class:
import java.util.ArrayList;
public class StoreTester{
public static void main(String[] args){
Store videostore = new Store();
System.out.print(videostore.toString());
System.out.print(videostore.get(0));
}
}
For some reason videostore.toString() works fine and prints out the list of objects I've added to it. Here is the method toString I wrote in my Store class:
public String toString(){
String item = "Items in store: " + "\n";
for(int j = 0; j < blockbuster.size(); j++){
item = item + blockbuster.get(j).getTitle() + "\n";
}
return item;
}
but as soon as I try to get() a specific object at an index or even use videostore.size(), i get the: method undefined error. Hopefully it is just a syntax error or something simple I've overlooked. Any help is appreciated.
Yes, Store does not have a method get
It can be implemented in Store as
public Item get (int index) {
// check for null, then
return blockbuster.get(index);
}
Store has-a ArrayList it is not Store is-a ArrayList
As #ElliottFrisch also mentions, you will need to implement a size method as well
public int size () {
// check for null, then
return blockbuster.size();
}

Create an object and put in an array

I want to create just an object,i am not sure if i am creating and it is right.My example ,lets say i have 2 class(Userinput and paper).0fcourse there is and the main.In this example No inherit (just 2 simple class).Am i create an object right?How i put in it in an array or in the same array?
package exercise;
public class Exercise{
static int N; //from keyboard .I have a class userinput.It doesnt need to write it here ,i have in the other class the problem
public static void main(String[] args) { // main class
Paper[] pin = new Paper[N]; //i create an array
Paper.setpencil(3); // i wrote the 3 .In this way i create 3 pencil?
Paper.getpencil(3);
Paper.setsomething(4); // i wrote the 4 .I create 4 ?
Paper.getsomething(4);
} }
public class Paper{ //in this class i am confused
public Paper(){} //default constructor
private int pencil;
private String something;
public int getpencil(){
return pencil;
}
public void setpencil(){
pencil=UserInput.getInteger():
}
public int getsomething(){
return something;
}
public void setsomething(){
something=UserInput.setInteger();
}
}
with this statement:
Paper[] pin = new Paper[N];
you create an array of object of class Paper.
You must also create an object for each array element like:
for (int i=0; i < N, i++)
{
pin[i] = new Paper();
}
And next you should refer to an element (e.g. first element that with index 0) of the array in this way:
pin[0].setpencil(3);

Java: Deleting Elements in an ArrayList using Their Value

I was asked to demonstrate a Singleton class design for my assignment. The version I submitted uses Strings and works fine, but I just can't get the reserveLane method to work properly with integers. Whenever I call the reserveLane method in the code below, it removes the element with the index of the integer passed into it instead of the element containing the value that matches the integer passed in. The program is supposed to print each message in the removeLane method once.
import java.util.*;
public class Race {
// store one instance
private static final Race INSTANCE = new Race(); // (this is the singleton)
List<Integer> lanes = new ArrayList<>();
public static Race getInstance() { // callers can get to
return INSTANCE; // the instance
}
private Race() {
lanes.add(1);
lanes.add(2);
}
public void removeLane(int lane) {
if(lanes.contains(lane)){
lanes.remove(lane);
System.out.println("Lane successfully reserved.");
} else {
System.out.println("Lane is already reserved.");
}
}
public static void main(String[] args) {
assignLane(1);
assignLane(1);
}
private static void assignLane(int lane) {
Race race = Race.getInstance();
race.removeLane(lane);
}
}
I'm wondering if I'm wasting my time trying to go this route or is there a way to fix it?
Integer integer = new Integer(lane);
lanes.remove(integer);
Your lanes is an arraylist of Integer objects, not int. Passing an int to Arraylist.remove(int index) will remove an object at that index, but if you pass an Integer object, the remove() function will delete the first occurrence of that object.
You are using primitive type to do your removal of element. You can convert it the Wrapper class and do it. Change the removeLane method as follows:
public void removeLane(Integer lane) {
if(lanes.contains(lane)){
lanes.remove(lane);
System.out.println("Lane successfully reserved.");
}
else{
System.out.println("Lane is already reserved.");
}
}
ArrayList Docs
E remove(int index)- Removes the element at the specified position in this list.
boolean remove(Object o) - Removes the first occurrence of the specified element from this list, if it is present.
As you have sent an int primitive type to method remove it has called remove(int index). Instead just send an Integer object and then it will call method remove(Object o) and it will work fine.
Working Code:
package stackoverflow;
import java.util.ArrayList;
import java.util.List;
public class Race {
private static final Race INSTANCE // store one instance
= new Race(); // (this is the singleton)
List<Integer> lanes = new ArrayList<>();
public static Race getInstance() { // callers can get to
return INSTANCE; // the instance
}
private Race() {
lanes.add(1);
lanes.add(2);
}
public void removeLane(int lane) {
if (lanes.contains(lane)) {
lanes.remove((Integer) lane);
System.out.println("Lane successfully reserved.");
} else {
System.out.println("Lane is already reserved.");
}
}
public static void main(String[] args) {
assignLane(1);
assignLane(1);
}
private static void assignLane(int lane) {
Race race = Race.getInstance();
race.removeLane(lane);
}
}

Should I create a method or variable for the table given below

I have an assignment which says that I need to create an queue class with instruction messages on it.
and instruction message is formed of following properties
-----------
>InstructionType integer
> ProductCode integer
> Quantity integer
> UOM byte
--------------------------------
Can I declare all the above given properties as variables and then pass it as a parameter in a function created for instruction message and place it in the instruction queue class. Can anyone give me a sample code for proceeding with this..and let me know if I think right or any other methodologies. Can be done? please help.
Can anyone suggest ,If am right.Can i use like this:
public class instructionqueue
{
LinkedList queue = new LinkedList()
/* how to add,retreive and delete the instructionmessage from the queue class*/
}
where insturctionmessage is a class
public class Instructionmessage
{
public int Instructiontype;
public Integer Productcode;
public Integer quantity;
public byte[] UOM = new byte[256];
public Integer Timestamp;
/*method to set and get the instruction type for the messages*/
public int getInstructiontype()
{
return Instructiontype;
}
public void setInstructiontype(int newInstructtype)
{
Instructiontype = newInstructtype;
}
/*method to set and get the product code for the messages*/
public int getProductcode()
{
return Productcode;
}
public void setProductCode(int newproductcode)
{
Productcode = newproductcode;
}
/*method to set and get the quantity for the messages*/
public int getquantity()
{
return quantity;
}
public void setquantity(int newquantity)
{
quantity = newquantity;
}
/*method to set and get the Timestamp for the messages*/
public int getTimestamp ()
{
return Timestamp;
}
public void setTimestamp(int newTimestamp)
{
Timestamp = newTimestamp;
}
/*method to set and get the UOM for the messages*/
public byte[] getUOM()
{
return UOM;
}
public void setUOM(byte[] newUOM)
{
UOM = newUOM;
}
}
Since the instruction message consists of 4 fields, you could create an Instruction class to encapsulate them. Then, for the queue you could use a list, and populate it with Instructions. For example, instantiate
LinkedList<Instruction> queue = new LinkedList<Instruction>();
You could then use queue.getFirst() and queue.addLast(...) to manipulate the queue's contents.
Create a POJO java class with all your variables. The create getters and setters for all variables. This will help you to set and get data using the methods.
Now create a Queue object in your main class and add(Object) method to add it in the queue.
Queue<String> sampleQueue = new LinkedList<String>();
sampleQueue.add("Joseph");
sampleQueue.add("Madhonna");
Note: Queue is an interface, so you cannot instantiate the object.
Possible exceptions can be thrown when you use this method. Refer this link for more details http://docs.oracle.com/javase/6/docs/api/java/util/Queue.html#add(E)
IllegalStateException - if the element cannot be added at this time
due to capacity restrictions List item
ClassCastException - if the class of
the specified element prevents it from being added to this queue
NullPointerException - if the specified element is null and this
queue does not permit null elements
IllegalArgumentException - if some property of this element prevents it from being added to this queue

Categories