open csv collection and continuous array - java

i dont quite understand by the given eg on opencsv site on how to use collection here List,eg is:
CSVReader reader = new CSVReader(new FileReader("yourfile.csv"));**
List myEntries = reader.readAll();**
I tried accessing a member of the List for eg System.out.println(myEntries.get(2)) but it gives me something like d1e604 and when i tested for existence of an element
boolean b = myEntries.contains("the element");** and it returns false.
what do i need to do to access the tokenized Strings?
by using readNext(), the elements are separated by "\n" and i want to assign the elements in a continuous no. of array.
while((tokened = reader.readNext()) != null){
int numOfArray = tokened.length;
System.out.println("number of items:"+ numOfArray) ;
for (int i = 0;i < numOfArray;i++) {
System.out.println(" tokenNo[" + i + "]: " + tokened[i]);
}
}

I think you missed a little fact about CSV. CSV is about lines AND columns. readNext() returns an array of strings representing a line. So I would guess, readAll() returns a list of string[].

Each element of your List myEntries is a String[].
i.e. That is an array of String.
that means you need a cast.
String[] entry = (String[]) myEntries.get(2);
Also -
System.out.println(myEntries.get(2)) but it gives me something like d1e604.
That's because the toString method is not properly overridden. That's the default behavior of the toString method as implemented in the Object class.

Related

How to solve Null Pointer Exception while using array?

Here its showing null pointer exception in the line arr[i] = "true";
String[] count = null;
String[] arr = null;
int i = 0;
rs2 = st2.executeQuery("SELECT COUNT(*) as y FROM " + usrtbl + " WHERE user_id NOT IN (SELECT user_id FROM " + usrroletbl + ")");
rs2.next();
if (rs2.getInt("y") == 0) {
arr[i] = "false";
count = arr;
i++;
} else {
arr[i] = "true";
count = arr;
i++;
}
Any help will be appreciated.
You need to initialize the String[] array
Approach 1
String[] errorSoon = new String[100]; // <--initialized statement, this is fixed size array, so you need to set the size accordingly, keeping memory usage in mind.
Approach2
use List
List<String> errorSoon = new ArrayList<String>();
Also as mentioned by #dave, if it is really required to have array here, or just a boolean variable can work for you.
You have defined arr to be null and you have not allocated it any memory. So of course, accessing arr[i] will result in a NullPointerException.
You could first run an SQL query to get the number of results and allocate the space, eg.
arr = new String[<count>];
Or you could use an ArrayList to hold the values. This is simpler as it will grow dynamically to hold your data.
As an aside, you should consider converting arr (or your ArrayList) to hold boolean. Then you can use true and false directly (rather than their string equivalents).
As #Dave said you have declared both the String arrays as null, so of course you will get NullPointerException. You have to know the size of your resultset first and then declare the array according to the size.
But instead of that I would recommend you to use ArrayList. Its simple and can dynamically add your result. You can do something like this-
List<String> list=new ArrayList<String>();
while(rs.next()){
if(// your condition){
list.add("something");
}
else{
list.add("something");
}
}
So it will keep on adding "something" in the list till the last row is covered.
Then you can easily iterate through the list as per your requirement.
Or you can also convert the ArrayList into an Array using the following command-
Object obj[]=list.toArray(); //Note that it will create an Array of Object datatype. You have to typecast it to your required datatype later if you want to print or manipulate the data.

Splitting by Tabs in Java

I have a file scanned line by line into an ArrayList.
I then create a new ArrayList in which I want to temporarily store that line into so that I may access certain values.
Ex. IDname(tab)IDnumber(tab)vote(tab)date
So, I create the temporary ArrayList named voteSubmission, and I go through every String in the fileRead array.
Why is it that I get the error incompatible type for my split method?
ArrayList<String> voteSubmission = new ArrayList<String>();
for(String x : fileRead)
{
voteSubmission = x.split("\t");
}
The split method returns an array, not an ArrayList.
Either work with an array or convert it to an ArrayList manually.
x.split("\t"); this function will return an array not array list
The split function states that:
Splits this string around matches of the given regular expression.
This method works as if by invoking the two-argument split method with
the given expression and a limit argument of zero. Trailing empty
strings are therefore not included in the resulting array.
Returns:
the array of strings computed by splitting this string around matches
of the given regular expression
You may try to change your code like this:
ArrayList<String> voteSubmission = new ArrayList<String>();
for(String x : fileRead)
{
for(String value: x.split("\t"))
{
voteSubmission.add(value);
}
}
The output of split() is of type string[] array and you are trying to assign to an ArrayList type, which is incompatible.
Change your code to
ArrayList<String> voteSubmission = new ArrayList<String>();
for(String x : fileRead)
{
String arr[] = x.split("\t");
if(arr != null && arr.length > 0)
{
for(String value: arr)
{
voteSubmission.add(value);
}
}
}
The error is: Type mismatch: cannot convert from String[] to ArrayList<String>
Which means that x.split("\t") provides a String[] array, but you assign it to an ArrayList.
If you'd like it to be an ArrayList, you'd have to convert it like this:
new ArrayList<String>(Arrays.asList(x.split("\t")));
But since you are doing this in a loop it is likely that you would like to store all Arrays within the ArrayList. To do this, you have to create an ArrayList of type String[], like this:
ArrayList<String[]> voteSubmission = new ArrayList<String[]>();
for(String x : fileRead){
voteSubmission.add((x.split("\t")));
}

instantiating Two arrays from two text files

I am trying to instantiate the String array cool with items from the file "cool.txt" and the same for the array warm except with the text file "warm.txt" the program works to an extent however many elements of the array are labeled as null like this
This is partially correct as they array has all the correct items; just millions of null's after
here is my code
int count2=0;
int count3=0;
String[] filename ={"Cool.txt","Warm.txt"};
String[] cool =new String[30];
String[] warm =new String [3000];
String[][] arrays = new String [][]{cool,warm};
BufferedReader fr;
try
{
for(int i=0; i<2; i++)
{
fr = new BufferedReader(new FileReader(filename[i]));
String line = fr.readLine();
while (line != null)
{
if (i<=0)
{arrays[i][count2]=line;
System.out.println("COOL");
count2++;}
if(i>=1)
{arrays[i][count3]=line;
System.out.println("WARM");
count3++;}
line = fr.readLine();
}
fr.close();
}
System.out.println(Arrays.asList(warm));
System.out.println(Arrays.asList(cool));
}
catch(Exception F){
System.out.println("NUL");
}
}
When you create an array of objects in Java, they are initialized to a default value. For integers, this is 0. For Objects, such as String, this is a null-reference. As your array is made to contain 30000 elements, it will have the elements from your file (about 5), and the rest will not be initialized (null).
If you wish to use a list of Objects that has a variable size, you can look up ArrayLists, or other types of Lists. If you were to replace the following lines:
String[] cool =new String[30];
String[] warm =new String [3000];
and
System.out.println(Arrays.asList(warm));
System.out.println(Arrays.asList(cool));
with
List<String> cool = new ArrayList<String>();
List<String> warm = new ArrayList<String>();
and
System.out.println(warm);
System.out.println(cool);
You would get the correct result.
You were already using lists in a way: the method call Arrays.asList converts the argument to an object of the type List.
At the end of the function you end up converting them to list objects. If you just use a List to start with you won't have "millions" of nulls. The reason why you get nulls is you can only allocate the array one time, so all slots are defaulted to null.

Buffer string to array list, and split

I am buffering a text file of into 'arraylist lines' i then need to split each line into a new arrayList parts, so that i can find information from each line and add the data to a model i have built, the reason i am using arrayLists is because of there expandable properties, meaning i wont need to worry about the size of either the line or the text file.
the code is below:
try(BufferedReader buffer =
new BufferedReader(new FileReader("src/Sample.txt")))
{
String currentLine;
ArrayList<String> lines = new ArrayList<String>();
ArrayList<String> parts = new ArrayList<String>();
//ListIterator<String> lineItr = lines.listIterator();
while((currentLine = buffer.readLine()) != null)
{
lines.add(currentLine);
for(String line : lines)
{
parts.addAll(line.split("\\s+"));
}
//lineItr.next();
//lineItr.set(currentLine);
//System.out.println(lineItr.next());
}
}
catch(IOException e)
{
e.printStackTrace();
}
}
i am having my troubles with parts.addAll(line.split("\s+");
i do not understand why the statement does not iterate through lines, splitting and adding each part of the string to the parts array list, am i misunderstanding something here?
thanks Babble
list.addAll() accepts a java.util.Collection where as str.split returns you an array is not a collection. Hence you can not add it directly to a list. You need to convert into a list first.
for(String line : lines)
{
parts.addAll(Arrays.asList(line.split("\\s+"));
}
String.split() returns Array of String . So you have to use Arrays.asList() to convert it into list .
parts.addAll(line.split("\\s+"));
Above line should be:
parts.addAll(Arrays.asList(line.split("\\s+")));
Or :
Collections.addAll(parts, line.split("\\s+"));
try this
parts.addAll(Arrays.asList(line.split("\\s+")));
List.addAll accepts a Collection but line.split("\\s+") returns String[]. You can do it this way
parts.addAll(Arrays.asList(line.split("\\s+")));
Every time a new line arrives, you append the whole thing all over again. Drop the inner "for" loop, and just split currentLine instead.
EDIT based on comment:
The Java Way would be implementing the year and month objects as containers. The simpler alternative is using string-keyed maps.

For-Each and Pointers in Java [duplicate]

This question already has answers here:
Why does the foreach statement not change the element value?
(6 answers)
Closed 5 years ago.
Ok, so I'm tyring to iterate through an ArrayList and remove a specefic element. However, I am having some trouble using the For-Each like structure. When I run the following code:
ArrayList<String> arr = new ArrayList<String>();
//... fill with some values (doesn't really matter)
for(String t : arr)
{
t = " some other value "; //hoping this would change the actual array
}
for(String t : arr)
{
System.out.println(t); //however, I still get the same array here
}
My question in, how can I make 't' a pointer to 'arr' so that I am able to change the values in a for-each loop? I know I could loop through the ArrayList using a different structure, but this one looks so clean and readable, it would just be nice to be able to make 't' a pointer.
All comments are appreciated! Even if you say I should just suck it up and use a different construct.
I think the best approach may be to use a for loop.
ArrayList<String> arr = new ArrayList<String>();
for (int i = 0; i < arr.size(); i++) {
String t = arr.get(i);
if (// your condition is met) {
arr.set(i, "your new value");
}
}
The problem is that you're trying to change the loop-scoped reference t to let it point to a new String instance. This ain't going to work. It does not refer the actual entry in the arraylist. You need to change the actual value of the reference. If String was mutable and provided a fictive set() method for that, you could in theory do
for (String t : arr) {
t.set("some other value");
}
or so, but that's not possible as it is immutable. Better get a handle of the entrypoint in the array itself using the normal for loop:
for (int i = 0; i < arr.size(); i++) {
arr.set(i, "some other value");
}
If you insist in using the enhanced for loop, then you need to replace String by StringBuilder, which is mutable:
for (StringBuilder t : arr) {
t.delete(0, t.length()).append("some other value");
}
Remember, Java is pass-by-value, not pass-by-reference.
For-each doesn't give you an index pointer, so you just can't use it to change an immutable value.
Either use a for-loop with an index or use a mutable type (like StringBuffer, not String)
An array of objects (like strings) in Java is a contiguous block containing an ordered series of references. So, when you have an array of 4 strings, what you really have is 4 references stored IN the array, and 4 string objects that are outside of the array but are referenced by its 4 elements.
What the for-each construct in Java does is create a local variable and, for each iteration, copy into that local variable the reference from the array cell that corresponds to that iteration. When you set the loop variable (t = " some other value") you are putting a reference to a new string, "some other value", into the local variable t, not into the array.
The contrasts with some other languages (like Perl) where the loop variable acts like an alias to the array/list element itself.
Your code is re-written by the compiler as something like this:
ArrayList<String> arr = new ArrayList<String>();
//... fill with some values (doesn't really matter)
for (final Iterator <String> i = arr.iterator(); i.hasNext();) {
String t;
t = i.next();
t = " some other value "; // just changes where t is pointing
}
To do what you want you would have to write the for loop like this:
for (final ListIterator<String> i = arr.iterator(); i.hasNext();) {
final String t;
t = i.next();
i.set("some other value");
}
Iterator does not have the set method, only ListIterator does.
Basically you want to remove the String t from the list arr. Just do a arr.remove(t) and you could be done. But you can't do it while iterating over the same list. You'll get an Exception if you try to modify the list this way.
You have two options:
clone your list, iterate through the clone and remove the 'specific' String from the original list
create a list for delete candidates, add all 'specific' Strings to that list and, after iterating through the original list, iterate through the wastebin and remove everything you've collected here from the original list.
Option 1 is the easist, the clone can be made like:
List<String> clone = new ArrayList<String>(arr);
You seem to misunderstand how objects/references work in Java, which is pretty fundamental to using the language effectively. However, this code here should do what you want (apologies for the lack of explanation):
ArrayList<String> arr = new ArrayList<String>();
//... fill with some values (doesn't really matter)
for(int i = 0; i < arr.size(); i++)
{
arr.set(i, " some other value "); // change the contents of the array
}
for(String t : arr)
{
System.out.println(t);
}
I believe, this is not related to immutable or mutable.
t = " some other value "; //hoping this would change the actual array
t does not hold the reference to actual object. Java copies the value from arraylist and puts that value into t so array list value does not get affect.
HTH
This has been answered well. Still here is my suggestion. The var t inside loop is only visible there. It will not be seen outside the loop. You could do t.set() if it was not String.
Use a StringBuffer rather than plain strings. This way the string within is mutable.
Strings are immutable. If you had a mutable type like StringBuilder/Buffer, you could change the string in your iteration. You do have references, remember.

Categories

Resources