ClassCastException: java.lang.Object[] cannot be cast to java.lang.Double - java

I am having a little trouble with my code. I have a hash map which has data. I want to get that data from the hash table and so far so good everything was working properly until I tried to get the coordinates of a point. I have made a class called "Segments" it contains a string "name" and an array of Doubles (longitude latitude). It is supposed to fill the variables with data from the hash table. In debug mode I saw the elements the longitude and latitude but it doesn't put them into the arrays I have specified and it prints out an error:
"ClassCastException: java.lang.Object[] cannot be cast to java.lang.Double"
Here is my code.
public class Segments
{
public String name;
public double[] latitude;
public double[] longitude;
public void Read(HashMap<String,Object> segment)
{
this.name = (String) segment.get("name");
Object[] coord = (Object[]) segment.get("coordinates");
try
{
for(int i = 0; i < coord.length; i++)
{
latitude[i] = (Double)coord[0];
longitude[i] = (Double)coord[1];
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
Can you tell me what am I doing wrong and how to fix my code?

I think the main issue is that your coord array doesn't contain coordinates but rather an array of array of coordinates. Therefore the correct way to address this would be:
for(int i = 0; i < coord.length; i++)
{
latitude[i] = (Double)coord[i][0];
longitude[i] = (Double)coord[i][1];
}
Notice the second-level array inside the loop.
EDIT: You may need to add an explicit cast to coord[i]. Try these - one of them might work for you:
latitude[i] = ((Double[])coord[i])[0];
longitude[i] = ((Double[])coord[i])[1];
or
latitude[i] = ((double[])coord[i])[0];
longitude[i] = ((double[])coord[i])[1];
or
latitude[i] = (Double)((Object[])coord[i])[0];
longitude[i] = (Double)((Object[])coord[i])[1];

You are trying to cast a primitive object to Object.
You can try to change your values do Double or cast to double[]
Also this is a very common mistake, remember that all primitives doesn't extend Object in Java
Try this code:
public class Segments
{
public String name;
public Double[] latitude;
public Double[] longitude;
public void Read(HashMap<String,Object> segment)
{
this.name = (String) segment.get("name");
Double[] coord = (Double[]) segment.get("coordinates");
try
{
for(int i = 0; i < coord.length; i++)
{
latitude[i] = coord[0];
longitude[i] = coord[1];
}
}
catch(Exception e)
{
e.printStackTrace();
}
}

Guys I found the solution and of course thank you for your help you pointed me to the right way. Sop the solution was that i had to declare the size of the array and the arrays (latitude, longitude) must be "double" not "Double" and so to fill the arrays (latitude, longitude) the code must look like:
public class Segments
{
public String name;
public double[] latitude;
public double[] longitude;
public void Read(HashMap<String,Object> segment)
{
this.name = (String) segment.get("name");
Object[] coord = (Object[]) segment.get("coordinates");
//Object[] coord2 = new Object[coord.length];
latitude = new double[coord.length];
longitude = new double[coord.length];
try
{
for(int i = 0; i < coord.length; i++)
{
latitude[i] = (Double)((Object[])coord[i])[0];
longitude[i] = (Double)((Object[])coord[i])[1];
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
}

Related

How to assign a predefined array to length of zero

I have this block of code and if the main method calls this method and if the parameter is null, then an empty array should be assigned to data. How would I go about doing this?
// Private double array data
private double data[];
// Default constructor that creates a double array having a single element of 0.0
public Stat() {
data = new double[0];
} // End of method
public class StatTester {
public void setData(double[] d) {
if (d == null) {
//where an empty array should be assigned to data
} // End of for loop
} // End of if condition
else {
double[] data = new double[d.length];
for (int c = 0; c < data.length; c++) {
data[c] = d[c];
} // End of for loop
this.data = data;
} // End of else condition
} // End of method
public static void main (String[] args) {
double[] data1 = {50.0, 60.0};
Stat stat1 = new Stat();
data1 = null;
stat1.setData(data1);
System.out.println("stat1 data = " + stat1.toString());
}
Should output:
stat1 data = [50.0, 60.0]
stat1 data = []
Thank you!
Do not redeclare data in setData.
Return as soon as you assign an empty array to data.
Demo:
import java.util.Arrays;
public class Stat {
private double data[];
public Stat() {
data = new double[0];
}
public void setData(double[] d) {
if (d == null) {
data = new double[0];
return;
}
data = new double[d.length];
for (int c = 0; c < data.length; c++) {
data[c] = d[c];
}
}
public static void main(String[] args) {
double[] data1 = { 50.0, 60.0 };
Stat stat1 = new Stat();
stat1.setData(data1);
System.out.println("stat1 data = " + Arrays.toString(stat1.data));
data1 = null;
stat1.setData(data1);
System.out.println("stat1 data = " + Arrays.toString(stat1.data));
}
}
Output:
stat1 data = [50.0, 60.0]
stat1 data = []
Not sure what your problem is.
To assign empty array (array of size 0) to data do same you do in constructor:
data = new double[0];
However, since you've already did that in construction, just do nothing if d == null.
One thing confusing about your code is that you seem to have class Stat with field data and an inner class StatTester that refers to data from Stat via this.data, and does not declare it's own field data. And method setData is in StatTester, not Stat - so your code won't compile.
I'm assuming what you actually wanted is something this:
import java.util.Arrays;
public class Stat {
// Private double array data
private double data[];
// Default constructor that creates a double array having a single element of 0.0
public Stat() {
data = new double[0];
} // End of method
public void setData(double[] d) {
if (d != null) {
this.data = java.util.Arrays.copyOf(d, d.length);
}
} // End of method
public String toString() {
return Arrays.toString(data);
}
public static void main(String[] args) {
double[] data1 = { 50.0, 60.0 };
Stat stat1 = new Stat();
stat1.setData(null);
System.out.println("stat1 data = " + stat1.toString()); // outputs empty array []
stat1.setData(data1);
System.out.println("stat1 data = " + stat1.toString()); // outputs [50.0, 60.0]
}
}
If you want to assign an empty array to data simply do what you already have: data = new double[0];
However as Java is pass by value, where you indicate you want to do this assignment will not work. The reason is the variables data and d and separate. This can be confusing as when they both point to the same array, changes can be made to the array via either reference. However what you are trying to do is not operate on the underlying array, but assign a new array back.
What you need to do is either change the return type of setData to double[] and assign it back or wrap data in another object/ array and then your assigment will work.
you need to make an array with length of zero if you want to print an empty array like [] instead of printing null value:
if (d == null) {
this.data = new double[0];
return;
}
you can also do it in other way just assigning the this.data to d like below and it work correctly but it will print null instead of []:
if (d == null) {
this.data = d;
return;
}

How to associate an element in one Array with an element in another array (Android Studio)

I have two arrays:
float [] E;
float [] Location;
The elements in array E are the following: {1900, 16400, 77666, 8000, 13200, 15600}
The elements in array Location are {Birmingham, Blackburn, London, Luton, Manchester, Newcastle}
These data have been extracted from my database where they are associated, meaning:
Birmingham - 1900
Blackburn - 16400
London - 77666
Luton- 8000
Manchester-13200
Newcastle-15600
I want to be able ensure that the locations are associated to the right data as I have shown above if that makes sense. Is there a way of doing that?
Thanks In Advance!
Well, they're already associated by index. The entry at index 0 in E is related to the entry at index 0 in Location.
But I would solve this by not having two arrays. Instead, I'd have a single array storing an object, which had (for example) both the float 1900 (I wouldn't use float, though; at least use double) and the string "Birmingham".
class SomeAppropriateName {
private double distance;
private String location;
SomeAppropriateName(double distance, String _location) {
this.distance = _distance;
this.location = _location;
}
// ...add getters and setters as appropriate...
}
Then:
SomeAppropriateName[] info;
You can use android.util.Pair<F,S> for that.
List<Pair<String,Double>> pairs = Arrays.asList(
new Pair("Birmingham", 1900),
new Pair("Blackburn", 16400),
new Pair("London", 77666),
new Pair("Luton", 8000),
new Pair("Manchester", 13200),
new Pair("Newcastle", 15600)
);
for (Pair<String, Double> pair : pairs) {
Log.d("log", pair.first + " - " + pair.second);
}
Simply with HashMap !
HashMap is an array with key value. You can iterate on it etc.. For example this code :
HashMap<Integer, String> hmap = new HashMap<Integer, String>();
/*Adding elements to HashMap*/
hmap.put(12, "Chaitanya");
hmap.put(2, "Rahul");
hmap.put(7, "Singh");
hmap.put(49, "Ajeet");
hmap.put(3, "Anuj");
/* Display content using Iterator*/
Set set = hmap.entrySet();
Iterator iterator = set.iterator();
while(iterator.hasNext()) {
Map.Entry mentry = (Map.Entry)iterator.next();
System.out.print("key is: "+ mentry.getKey() + " & Value is: ");
System.out.println(mentry.getValue());
}
/* Get values based on key*/
String var= hmap.get(2);
System.out.println("Value at index 2 is: "+var);
/* Remove values based on key*/
hmap.remove(3);
System.out.println("Map key and values after removal:");
Set set2 = hmap.entrySet();
Iterator iterator2 = set2.iterator();
while(iterator2.hasNext()) {
Map.Entry mentry2 = (Map.Entry)iterator2.next();
System.out.print("Key is: "+mentry2.getKey() + " & Value is: ");
System.out.println(mentry2.getValue());
}
Good Luck
i don't know how you're querying your database, but i assume you're making one query to get both the location and the distance.
//1. create a model to represent the Location and its corresponding distance
public class LocationDistance {
private float distance;
private String location;
public LocationDistance(float distance, String location) {
this.distance = distance;
this.location = location;
}
public String getLocation(){
return this.location;
}
public float getDistance(){
return this.distance;
}
public void setLocation(String loc){
this.location=loc;
}
public void setDistance(float distance){
this.distance=distance;
}
}
//2. Loop over the two arrays and create a list of LocationDistance
List<LocationDistance> locationDistance=new ArrayList<LocationDistance>();
float[] e = { 1900f, 16400f, 77666f, 8000f, 13200f, 15600f };
String[] location = { "Birmingham", "Blackburn", "London", "Luton", "Manchester", "Newcastle" };
for(int i=0; i<e.length;i++){
locationDistance.add(new LocationDistance(e[i],location[i]));
}
is e a float, the same as location?
you should define a Pojo class for that
class Pojo {
private final float e;
private final String city;
public Pojo(float e, String city) {
this.e = e;
this.city = city;
}
public static void main(String[] args) {
final float[] e = { 1900f, 16400f, 77666f, 8000f, 13200f, 15600f };
final String[] location = { "Birmingham", "Blackburn", "London", "Luton", "Manchester", "Newcastle" };
final Pojo[] p = new Pojo[e.length];
for (int i = 0; i < e.length; i++) {
p[i] = new Pojo(e[i], location[i]);
}
}
}

Trying to add multiple doubles to an array in java

I'm trying to add a list of purchases to an array and then be able to perform some calculations based on the doubles in the array. Im having trouble trying to add purchases to the double array
Here's what I have:
public abstract class Customer {
protected String category;
protected String acctNumber;
protected String name;
protected double[] purchases;
protected static final double SALES_TAX_RATE = 0.08;
/**
*Reads in customer data.
*#param acctNumberIn customers account number.
*#param nameIn customers name.
*/
public Customer(String acctNumberIn, String nameIn) {
acctNumber = acctNumberIn;
name = nameIn;
purchases = new double[0];
}
Add purchases method where I'm having problems:
public void addPurchases(double ... pur) {
purchases = Arrays.copyOf(purchases, purchases.length + 1);
int a = purchases.length;
for (int i = 0; i < purchases.length; i++) {
purchases[a] = pur;
}
}
The problem is that pur is of type double[]. So you will need to create a new array with the size of purchases + pur, and copy each element of pur to the end of purchases.
Please try the following code:
public void addPurchases(double ... pur) {
int purchasesLength = purchases.length;
int combinedLength = pur.length + purchasesLength;
purchases = Arrays.copyOf(purchases, combinedLength);
for (int i = purchasesLength, j = 0; i < combinedLength; i++, j++) {
purchases[i] = pur[j];
}
}
Using an ArrayList instead of an array would be much simpler, as well as improve your code performance and quality. To create one to hold your purchases you could do
protected ArrayList<Double> purchases = new ArrayList<Double>();
And then your addPurchases method can easily be simplified to:
public void addPurchases(double... pur) {
for (double purchase : pur) {
purchases.add(purchase);
}
}
pur is an array, double... pur is away that allows you to pass zero or more values to a method, but which are treated as an array from within the method.
With this in mind, you are attempting to assign every element in your purchases array to the same value pur (or a double[]) which obviously won't work.
Instead, you need to get the current length of the array, re-size the array by the length of pur (purchases.length + pur.length), then from the previously last position begin adding in the new elements from pur
Maybe something like...
public void addPurchases(double... pur) {
int start = purchases.length;
purchases = Arrays.copyOf(purchases, purchases.length + pur.length);
for (int i = start; i < purchases.length; i++) {
purchases[i] = pur[i - start];
}
}
Now, any time you think this might be a good idea, you should consider using a List of some kind instead, maybe something like...
public static class Customer {
protected String category;
protected String acctNumber;
protected String name;
protected List<Double> purchases;
protected static final double SALES_TAX_RATE = 0.08;
/**
* Reads in customer data.
*
* #param acctNumberIn customers account number.
* #param nameIn customers name.
*/
public Customer(String acctNumberIn, String nameIn) {
acctNumber = acctNumberIn;
name = nameIn;
purchases = new ArrayList<>(25);
}
public void addPurchases(double... pur) {
for (double p : pur) {
purchases.add(p);
}
}
}
Have a look at the Collections Trail for more details
You can simply do:
public void addPurchases(double ... pur) {
int a = purchases.length;
purchases = Arrays.copyOf(purchases, purchases.length + pur.length);
for (int i = 0; i < pur.length; i++) {
purchases[a + i] = pur[i];
}
}
However, DO NOT use arrays and resize it manually. If you need to insert unknown number of items into a collection, use dynamic-size collections like java.util.List or java.util.ArrayList.

Null pointer exception for Array of Objects

I am new to using arrays of objects but can't figure out what I am doing wrong and why I keep getting a Null pointer exception. I am trying to create an Theatre class with an array of spotlight objects that are either set to on or off. But - whenever I call on this array I get a null pointer exception.
package theatreLights;
public class TheatreSpotlightApp {
public static void main(String[] args) {
Theatre theTheatre = new Theatre(8);
System.out.println("element 5 " + theTheatre.arrayOfSpotlights[5].toString());
}
}
package theatreLights;
public class Theatre {
spotlight[] arrayOfSpotlights;
public Theatre(int N){
arrayOfSpotlights = new spotlight[N];
for (int i = 0; i < arrayOfSpotlights.length; i++) {
arrayOfSpotlights[i].turnOn();
}
}
}
package theatreLights;
public class spotlight {
int state;
public spotlight(){
state = 0;
}
public void turnOn(){
state = 1;
}
void turnOff(){
state = 0;
}
public String toString(){
String stringState = "";
if(state == 0){
stringState = "is off";
}
else if(state==1){
stringState = "is on";
}
return stringState;
}
}
I must be doing something basic wrong in creating the array but can't figure it out.
replace
arrayOfSpotlights[i].turnOn();
with
arrayOfSpotLights[i] = new Spotlight();
arrayOfSpotlights[i].turnOn();
The line
arrayOfSpotlights = new spotlight[N];
will create an array of spotlights. It will however not populate this array with spotlights.
When you do "arrayOfSpotlights = new spotlight[N];" you init an array of length N, what you need to do is also init each object in it:
for i=0; i<N; i++
arrayOfSpotlights[i] = new spotlight();
arrayOfSpotlights[i].turnOn();
Hope I'm correct :)
You are not creating an spotlight objects.
arrayOfSpotlights = new spotlight[N];
This just creates an array of references to spotlights, not the objects which are referenced.
The simple solution is
for (int i = 0; i < arrayOfSpotlights.length; i++) {
arrayOfSpotlights[i] = new spotlight();
arrayOfSpotlights[i].turnOn();
}
BTW You should use TitleCase for class names.
You could write your class like this, without using cryptic code like 0 and 1
public class Spotlight {
private String state;
public Spotlight() {
turnOff();
}
public void turnOn() {
state = "on";
}
void turnOff() {
state = "off";
}
public String toString() {
return "is " + state;
}
}
You declared the array arrayOfSpotlights, but didn't initialize the members of the array (so they are null - and you get the exception).
Change it to:
public class Theatre {
spotlight[] arrayOfSpotlights;
public Theatre(int N){
arrayOfSpotlights = new spotlight[N];
for (int i = 0; i < arrayOfSpotlights.length; i++) {
arrayOfSpotlights[i]=new spotlight();
arrayOfSpotlights[i].turnOn();
}
}
}
and it should work.

Looping through two arrays

I have two different arrays an ArrayList of doubles and an Array of Strings
public class tester {
private final static String TIME[]={ "8:00", "9:00", "10:00", "11:00",
"12:00", "13:00", "14:00", "15:00", "16:00", "17:00", "18:00", "19:00" };
public static void main(String[] args){
ArrayList<Double> stat = new ArrayList<>();
stat.add(1.0);
stat.add(2.0);
stat.add(3.0);
stat.add(4.0);
stat.add(5.0);
stat.add(6.0);
stat.add(7.0);
stat.add(8.0);
stat.add(9.0);
stat.add(10.0);
stat.add(11.0);
stat.add(12.0);
int i = 0;
for (String time : TIME) {
System.out.println(time+" "+stat.get(i));
i++;
}
My question is quite simple is this the best way to loop through each array if I want to get the same position of each array to match? so that stat.get(0) ==TIME.get(0)?
Update
First of all thank you all for your quick response i like the idea of creating a class however there is something you need to know.
The thing you saw was a test class that i use to test my data.
i KNOW that the two arrays will ALWAYS be the same size due to the fact that the stat ArrayList normally defined like the following:
stat is a calculated value of data gained from the database the value of stat is based on time and then sent back to the GUI to be put into a graph and a table.
This means that for each of the TIME there is an exisiting value so that stat.get(0) is ALWAYS equal to TIME.get(0) == "8:00".
With this in mind do you still think i should create a class or should i keep the class showed below and then add a HashMap containing the data then iterate over that map to insert the data in my GUI?
public class Statistics {
private ArrayList<CallQueue> queues = new ArrayList<CallQueue>();
private ArrayList<Double> averageData = new ArrayList<Double>();
private Provider p;
public Statistics(){
try {
this.p = new Provider();
} catch (DopeDBException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* This recursive method calculates the average of each time table and then adds its to the arrayList in the following order:
* 8.00 = 0
* 9.00 = 1
* 10.00 = 2
* 11.00 = 3
* 12.00 = 4
* 13.00 = 5
* 14.00 = 6
* ect.
* #param time
*/
public void calculateAverage(){
int data = 0;
for (int i = 8; i < 20; i++) {
for (CallQueue cq : queues) {
data += cq.getCallsByTime(i);
}
if (data == 0) {
Main.createErrorMessage("Fejl i dataen! \r\n kontakt venligst ansvarlige i Dope");
}
averageData.add((double) data/11);
}
}
/**
* #author MRCR
* This method recives the object list from the database and sets the currentlist to the list recived.
*/
public void setQueues(Calendar start, Calendar end){
try {
queues = p.getInformation(start, end, queues);
} catch (DopeDBException e) {
// TODO Auto-generated catch block
Main.createErrorMessage("Message");
} catch (DopeResultSetException e) {
// TODO Auto-generated catch block
Main.createErrorMessage("Message");
}
}
/**
* This method returns the calculated DataList list.
* #author MRCR
* #return averageData
*/
public ArrayList<Double>getData(Calendar start, Calendar end){
setQueues(start, end);
calculateAverage();
return averageData;
}
}
import java.util.HashMap;
public class CallQueue {
private String type;
private HashMap<Integer, Integer> data = new HashMap<Integer,Integer>();
public CallQueue(String type){
this.type = type;
}
public String getType(){
return type;
}
public int getCallsByTime(int time){
return data.get(time);
}
public void addCallsByTime(int hourOfDay, int callAmount) {
data.put(hourOfDay, callAmount);
}
}
I would first check that the lengths of the 2 arrays are the same.
Then iterate using a for loop:
final int timeLength = TIME.length;
if (timeLength != stat.size()) {
//something may not be right
}
for (int i = 0; i < timeLength; i++) {
System.out.println(time[i]+" "+stat.get(i));
}
for (int i = 0; i < TIME.length; i++) {
// use i to access TIME[i] and stat.get(i)
}
but you have to ensure that those arrays are of the same length
You would need to consider the length part also. You would only need to iterate upto the maximum length possible that covers both array, and list.
So, you can first find the lower length between them. And then iterate till that length: -
int lower = TIME.length < stat.size()? TIME.length: stat.size();
for (int i = 0; i < lower; i++) {
System.out.println(TIME[i] + " : " + stat.get(i);
}
Now that was the part of iterating over two arrays.
Now I would say, if you have to iterate over two arrays simultaneously, just make a class with the attributes, you have created arrays for.
So, create a class with attributes: - time, and stats. And then create a List<YourClass>. And iterate over the list of the class instances.
if (TIME.length!=stat.size()) {
// handle error
}
int count = stat.size();
for (int i=0; i<count; ++i) {
double d = stat.get(i);
String s = TIME[i];
}
However
As pointed out in a comment, you should define a class that will gather the information of both arrays.
For instance:
public class MyTime {
private double value;
private String label;
}
Or
In that particular case, I suspect you could use time formatting functions to replace your string array.
String.format("%1$d:00", (int) myDouble);

Categories