I am creating a class to sort some data.
class data{
public String text;
public String day;
public String direction;
}
dados vetor[]={};
Now I have to have to change a varible and I am doing it this way:
vetor[0].text="dumb text";
But I am gettting this error:
Attempt to write to field java.lang.String on a null object reference
Unless you reassigned the array to something else, this is your problem.
dados vetor[]={};
You create an empty array - there is no data object at vetor[0] for you to set the text of. If you know the number of elements you'll have when you declare the array, you can use the following to create an array to hold all of them.
dados[] vetor = new dados[10];
To actually create an element in that array and set its text, you need to create a new object.
vetor[0] = new data();
vetor[0].text = "Some text";
Alternatively, create and set the values for the data object before adding it to the array:
data myData = new data();
myData.text = "Some text";
vetor[0] = myData;
You probably did something like :
vetor[0] = someInstanceOfData.text; // Store value in array
However now vetor[0] contains the value of the text field (i.e. a String).
You can not access the text field later by doing vetor[0]. This refers to the String that is stored in that array. So if later the value of the text field changes, the vector will still contain the old.
Hence vetor[0].text="dumb text"; is not assigning the text field of some instance of the data class, but instead is trying to assign a new value to the String that results from vetor[0].
EDIT : If you want to change the value of the text field :
Data test = new Data(); // Make an instance of the Data class
test.text = "A String"; // Assign a value
If you want to make an array (of strings? or data objects?)
Data[] arr = {new Data(), new Data(), new Data()}; // Using the litteral
String[] arrOfStrings = {test.text, test.day, test.direction};
If you want to access/assign e.g. text from a data object storen in arr
arr[0].text = "Another String";
arrOfStrings[0].text = ...; // Not possible because it is storing strings not Data objects!
If you don't know the length before hand, you can not use an array (as they are of fixed length). Instead you could use List's which are of variable length.
List<Integer> test = new ArrayList<Integer>();
test.add(1); // Add elements
test.size(); // How long is my array at the moment?
test.get(0); // Access first element (index 0) --> 1
Applying this to your code :
dados testObject = new dados(); // create a "dados" object
List<dados> testList = new ArrayList<dados>();
testList.add(testObject);
testList.get(0); // Get object on index 0 (hence the first), hence "testObject"
To sort the ArrayList of dados objects you should implement a custom comparator to sort the objects like you want
public class OwnComparator implements Comparator<Dados> {
#Override
public int compare(Dados obj1, Dados obj2) {
return obj1.text.compareTo(obj2.text); // Sort based on "text" field
}
}
The actual sorting
Collections.sort(testList, new OwnComparator());
I am assuming your class name is "dados" and not "data".
Your array does not have any elements, hence the error.
Initialize your array to a certain number of elements and then assign the text property.
dados[] vetor = new dados[10];
vetor[0] = new dados();
vetor [0].text = "xx";
dados[] vetor2 = {new dados(), new dados()}; // initialize to 2 elements
vetor2[0].text = "xx";
Related
I have array variable declared like this:
public class carshop {
int numofcars = 0;
int maxcars = 10;
ACar[] allCars;
private CarShop;
public CarShop() { //Car Constructor
maxcars = maxE;
allCars = new ACar[maxcars];
}
}
In my coding example, every time a user adds a new car (via string input), it will increase the numofcars by 1. I have tried changing the array type into a arraylist
ArrayList<ACar> allCars = new ArrayList<ACar>(Arrays.asList());
I changed the allCars = new ACar[maxcars]; line into this: allCars = ACar.add(maxcars);
However now eclipse is giving me errors saying "The method add(int) is undefined for the type ACar".
Can you tell me what I have done wrong? Sorry if I have explained this poorly.
ACar is an array so it doesn't have the add() method and you need to insert values by doing ACar[x] = value;
If you want to easily convert an array to a List you can just do:
List<ACar> carList = Arrays.asList(allCars);
or for ArrayList specifically:
ArrayList<ACar> carList = new ArrayList<ACar>(Arrays.asList(allCars));
However you should also think about why you have both an array and an ArrayList. You could instead just be doing:
List<ACar> carList = new ArrayList<ACar>(maxCars);
The maxCars variable is optional, you don't need to set the initial size of an ArrayList unless you are trying to optimise the code.
I'm successfully getting the values from CSV file in to List<String[]>, but having problem in moving values from List<String[]> to String[] or to get single value from List. I want to copy these values in to string array to perform some functions on it.
My values are in scoreList
final List<String[]> scoreList = csvFile.read();
Now I want to get single value from this scoreList. I have tried this approaches but could not get the value
String[] value=scoreList.get(1);
You want a single value but you are declearing an array an you are tring to assign string to string array. If you want a single value, try this;
String x = scoreList.get(1);
or
if you want to convert listarray to string array try this;
String[] myArray = new String[scoreList.size()];
for(int i=0; i<scoreList.size();i++)
{
myArray[i]=scoreList.get(i);
}
Suppose you want to collect values of the 2nd column (index 1) then you can try this
// Collect values to this list.
List<String> scores = new ArrayList<String>();
final List<String[]> scoreList = csvFile.read();
// For each row in the csv file
for (String [] scoreRow : scoreList ) {
// var added here for readability. Get second column value
String value = scoreRow[1];
scores.add(value);
}
array=[]
sent to servlet >>>>
///////// how i get [0]-[3] in array value in array [0-50]
for(????)
{ var A = get[0].toString;
var b = get[1].toString;
var c = get[2].toString;
var d = get[3].toString;
}
You can use Lists class from Guava
Object[] array = new Objects[50];
//... somehow fill array with real data
List<List<Object>> parts = Lists.partition(Arrays.asList(array), 4);
for(List<Object> part: parts){ //List 'part' will always contain not more than 4 elements
proccessPart(part); //passing elements to the method wich interacts with database
}
With the limited given information, If the question is how to processs an array which contains 50 objects with 4 untouched continuous objects sequentially
Object[] array = new Object[50];
//populate array
for(int i=3;i<50;i+=4) {
Object a = array[i-3];
Object b = array[i-2];
Object c = array[i-1];
Object d = array[i];
//variables may not be required as you can directly use array[i]
}
I have the below pojo which consists of the below members so below is the pojo with few members in it
public class TnvoicetNotify {
private List<TvNotifyContact> toMap = new ArrayList<TvNotifyContact>();
private List<TvNotifyContact> ccMap = new ArrayList<TvNotifyContact>();
}
now in some other class i am getting the object of above class TnvoicetNotify in a method signature as parameter as shown below .. So i want to write the code of extraction from list and storing them in string array within this method itself
public void InvPostPayNotification(TnvoicetNotify TnvoicetNotify)
{
String[] mailTo = it should contain all the contents of list named toMap
String[] mailCC = it should contain all the contents of list named ccMap
}
now in the above class i need to extract the toMap which is of type list in the above pojo named TnvoicetNotify and i want to store each item if arraylist in a string array as shown in below fashion
for example first item in list is A1 and second is A2 and third is A3
so it should be stored in string array as
String[] mailTo = {"A1","A2","A3"};
similarly i want to achieve the same for cc section also as in above pojo it is in list i want to store in the below fashion
String[] mailCc = {"C1","C2","C3"};
so pls advise how to achieve this within InvPostPayNotification method
Pseudo code, because I don't know details for TnvoicetNotify:
public void invPostPayNotification(final TnvoicetNotify tnvoicetNotify)
{
final List<String> mailToList = new ArrayList<>();
for (final TvNotifyContact tv : tnvoicetNotify.getToMap()) { // To replace: getToMap()
mailToList.add(tv.getEmail()); // To replace: getEmail()
}
final String[] mailTo = mailToList.toArray(new String[mailToList.size()])
// same for mailCc then use both arrays
}
If you are using Java 8, you could simply use a one liner :
String[] mailCC = ccMap.stream().map(TvNotifyContact::getEmail).toArray(String[]::new);
I am trying to cast kx.c class flip object to a string:
String test = (String) c.at(flip[0],1)
However I am getting an error stating that I cannot cast C objects to String. Does anyone know what I can cast a kx C object to return a string?
Not too sure what you mean exactly by "C objects" but I assume that it is a char array - the Java type to represent a Kdb string. Here is what you can do:
Object[] data = this.flip.y;
Object[] columnData = (Object[]) data[row];
char[] data = (char[]) columnData[i];
return String.valueOf(data);
If you are trying to retrieve a kdb symbol then it will be a String array.
Object[] data = this.flip.y;
Object[] columnData = (Object[]) data[row];
String data = (String) columnData[i];
return data;
A c.Flip is a mapping from keys to values. In particular, it has String keys and Object values, stored in two arrays inside the Flip (called x and y respectively).
If you want to get the value for the key "foo", then you can do something like this:
c.Flip myFlip = ...; // Get hold of your flip
Object value = myFlip.at("foo"); // Throws ArrayIndexOutOfBoundsException if "foo" is not found
If you happen to know that the value will be a String, then you can cast it:
String strValue = (String) value; // Throws ClassCastException if value isn't a String
You can also combine the last two lines into one, like so:
String strValue = (String) myFlip.at("foo");