java multidimensional array declaration 1*3 dimension? - java

hi i am new to java.After so research about what i am facing, i try post to ask some question.
recently i am doing a text analyse software.
and i try to get done with a 1*3 dimensional array.
something like
[0]
[][][]
[1]
[][][]
[2]
[][][]
[3]
[][][]
the three column in the second dimension of each is use for saving the details of the first dimension.
but the second dimension array size is yet unknown which mean that, idont know how many i will find from the text that i am gonna search.it will increase once the target found.
is this the stupid way for doing this.
i know java can declare array like int [][] abc = new [5][].
but it just can declare only for one unknown dimension.
then i try to do something like this
String [] abc = new string [4]
then i first make a presumption that the size is that in the first column in the second dimension.
abc[0] = String [10][][] inside1;
abc[1] = String [10][][] inside2;
abc[2] = String [10][][] inside3;
abc[3] = String [10][][] inside4;
but still getting error when i compile it.
how can i do the declaration or there got better to done this easy.
if i miss any post in the internet about this. please show me any keyword or link for me to take a look.

What is it that you are trying to implement? Sounds like you instead should use one of the collection classes together with value objects that represent your data.

I think i understand what you are trying to do and its like this:
String[][] value = new String[4][3];
Java doenst have multidimensional arrays, its Arrays Within Arrays.

If you're trying to parse a text file and you know what each column signifies, you should create a new object which contains that data. Arrays of arrays are an unnecessarily painful hack and your code is much more maintainable if you just do what Java is designed to be used for--write a class.

Example for a 10x13 matrix:
String [] [] abd = new String [10] [13];
EDIT: I chose 10x13, because 1x3 doesn't make much sense, being the first value 1.

Why don't you create an Object that has a 'name' property (or 'index' if you prefer), and a 'list' property of type List?
public class YourMultiDimensionalArrayObject {
private int index;
private List<String> vals;
public YourMultiDimensionalArrayObject(int _index) {
index = _index;
}
public void setValues(List<String> _vals) {
vals = _vals;
}
public int getIndex() {
return index;
}
public List<String> getVals() {
return vals;
}
}

You can use ArrayList to store an array of int values of unknown length. You can use an ArrayList> to store an indefinite number of int arrays.

I would create either a List<List<String>> or a Map<String, List<String>>, assuming the values you want to store and look-up by are Strings.

Related

how to query ArrayList<Funds> and store in an array

I have an ArrayList which stores 100 instances of a POJO named Funds. Here is what Funds looks like:
public class Funds
{
private String InvestmentName;
private String PrimaryInvestmentObjective;
private String AgencyOrMissionRelatedNeeds;
}
here is what my ArrayList looks like: ArrayList<Funds>
I need to get a complete list of InvestmentName from fundList, and I need to store all 100 InvestmentNames in an array. I tried to look to see if ArrayList had some kind of filter but couldn't find any.
please you can use java 8 stream api like
List<String> names= funds.stream().map(Funds:InvestmentName).collect(Collectors.toList());
please note this code is not test but it should work fine
It looks like you need to write a get method for your InvestmentName member and you also need to write a method that iterates through the ArrayList and puts each InvestmentName into an array.
So you have an ArrayList<Funds> and you want to transform that into an ArrayList<String> or String[] of investment names, is that right?
Have you tried something like this?
ArrayList<String> investmentNames = new ArrayList<>();
for (Funds f : fundsList) {
investmentNames.add(f.getInvestmentName());
}
If you really want to convert the result into an array (String[]) afterwards you would call this:
String[] investmentNamesArray = investmentNames.toArray(new String[investmentNames.size()]);
However you should avoid mixing arrays and Lists (Effective Java Item 25: Prefer lists to arrays) and just use investmentNames directly.

ArrayList compiler error

I am trying to make an array list in Java in two spots, but I don't know what I am doing wrong. It says an array is required, but I don't know what that means because I am using an array list.
This is the line that's being messed up:
static char rSpaces(String problem, int count)
{
num.add(problem.charAt(count));
char no = num[count];
return no;
}
If this helps, this is the line I created the array list in (I already imported it):
static ArrayList<Character> num = new ArrayList<Character>();
num[count] is wrong, since num is not an array. Use num.get(count) instead.
An ArrayList is not an array, so you can't use the array element [] syntax here.
With an ArrayList, use the get method to access an element.
You should use ArrayList.get to access the elements of an ArrayList. Change that to:
char no = num.get(count);
Java array and ArrayList are different things.
You could access the size of the ArrayList by using method size as follows:
static char rSpaces(String problem, int count)
{
num.add(problem.charAt(count));
char no = num.get(count);
return no;
}
If you want to access it as an array, you could "export" it using the toArray method as follows:
...
Character[] myArray = num.toArray(new Character[]{})
Character c = myArray[count];
...
To access element of array use index operation using [] operator num[count] while in case of ArrayList you need to use get(count) method.

Android Java Adding a single dimesional byte array to a double dimension byte array

I have a requirement to append another byte array(one dimensional) to existing byte array which happens to be two dimensional.
public static byte[][] ALL_MESSAGES = new byte[][] {SMART_POSTER_NO_TEXT, ENGLISH_PLAIN_TEXT, SMART_POSTER_URL_AND_TEXT};
public void AddOtherMessages()
{
OtherMessageClass messages = new OtherMessageClass();
for(NMessage m : messages.Ntexts)
{
ArrayUtil.addAll(ALL_MESSAGES, m);
}
}
Obviously the code above does not work because I am using the AddAll to add two arrays, one a multidimensional, to another, a single dimension array. I need some help with appending the m to ALL_MESSAGES please.
Also, what Java Namespace do I need to import to be able to do this?
ArrayUtil is a part of 'org.apache.commons.lang' package. So you,ll also have to include the corressponding jar file to use the same.
You will require apache-commons-lang.jar and you will have to import org.apache.commons.lang.ArrayUtils. For more details refer http://commons.apache.org/lang/api-2.5/org/apache/commons/lang/ArrayUtils.html
for(NMessage m : messages.Ntexts)
{
ArrayUtil.addAll(ALL_MESSAGES, m);
}
the above code will work not work m is not a byte[][]. If m is byte[] you should use 'add()' method instead. if messages.Ntexts returns byte[][] you could also use 'addAll()' method.
If i understood you correctly, you want to add extra arrays to ALL_MESSAGES? In that case, i think you should consider using a List:
List<byte[]> list = new ArrayList<byte[]>();
then you can add as many byte[] arrays as you like:
list.add(new byte[] {1,2,3}); //just an example
and you can just as easily retrieve them all:
for(byte [] array : list)
{
//do whatever you like with your individual arrays
}
You can also get a single element (like you would with the index operator):
byte [] array = list.get(0);

How to convert a List of String arrays to a List of objects

I want to convert a List to a List so that each object on my new list includes the first element of each String[].
Do you know if this is possible to do in java?
for example:
public List<String[]> readFile(){
String[]array1={"A","1.3","2.4","2.3"};
String[]array2={"B","1.43","3.4","2.8"};
String[]array3={"C","5.23","2.45","2.9"};
List<String[]>ReadFile= new ArrayList<String[]>();
ReadFile.add(array1);
ReadFile.add(array2);
ReadFile.add(array3);
return ReadFile;
}
Now I want a method which will take the List ReadFile from above to somehow split the arrays of strings into an ID which will be the first element "A", "B", "C" and another part which would be the string array of numbers which I will put through another method to convert numbers from String to type Double. I have already got the method to convert to double but I need to be able to keep track of the ID field because the ID field will be used to identify the array of numbers.
A friend suggested that I create an Object where each objects has one part as a String ID and the other part as an array. That is the part which I do not know how to do.
Can anybody help please?
below is the method declaration which I believe I should have so the return type will be List where each array has been converted to an Object with two parts.
public List<Object> CreateObject(List<String[]>ReadFile){
}
Thanks,
Jetnori.
Hi all, Thank you for taking your time to help.
I can see the benefit of using HashTables. I am as of now trying to implement it. I know i might be sidetracking a little but just to explain what I am trying to do:
In my project I have CSV file with data about gene expression levels. The method that I use from OpenCSV to read the file returns a List(String[]) where each String[] is one row in the file. The first element of each row is variable name (recA, ybjE etc). The rest of the row will be numbers data related to that variable. I want to calculate Pearson's correlation between each of the number arrays. The method which I have got implemented already does that for me but the problem that I have now is that I had to remove the string values from my arrays before I could convert to double by iterating over the array. After I have managed to calculate the correlation between each array of doubles by still keeping the ID linked to the row, I want to be able to draw an undirected node graph between the genes that have a correlation higher than a threshold which I will set (for example correlation higher than 0.80). I don't know if i am biting more than i can chew but I have 30 days to do it and I believe that with the help of people like you guys I will get through it.
Sorry for going on for a bit.
thanks,
Jetnori.
I agree with the answer Alb provided, however this is what your friend has suggested, first you need a class to represent the data. I have included a constructor that parses the data and one that accepts already parsed data, depending on how you like to think of things.
public class NumberList {
private double[] numbers;
private String key;
public NumberList(Strig key, double[] numbers){
this.ley = key;
this.numbers = numbers;
}
public NumberList(String[] inputList) {
key = inputList[0];
numbers = new double[inputList.length-1];
for(int i=1;i<inputList.length;i++){
numers[i-1] = Double.parseDouble(inputList[i]);
}
}
public String getKey() {
return key;
}
public double[] getNumbers() {
return numbers;
}
}
Then you need your function to generate the list:
public List<NumberList> CreateObject(List<String[]> ReadFile){
ArrayList<NumberList> returnList = new ArrayList<NumberList>(ReadFile.size());
for (String[] input : ReadFile) {
returnList.add(new NumberList(input));
}
return returnList;
}
Note this uses the constructor that parses the data, if you use the other constructor then the "CreateObject" function would need to include the parsing logic.
Finally on a side note the standard convention in java is that the only thing that is capitalized are class names and final static fields (which appear in all caps sepearted by underscores), so conventionally the method signature would be:
public List<NumberList> createObject(List<String[]> readFile){
...
}
Sounds like you need a Map instead of a List, it lets you index things by a key (in your case ID).
Map<String, String[]> map = new Hashmap<String, String[]>();
for( String[] array : ReadFile ){
map.put( array[0], array );
}
then to get the array of values for 'A' you would do:
String[] values = map.get( "a" );
If you want the values to be doubles instead of strings you'll want to change the array before putting it (the map.put call) I'd advise using a list or other collections instead of an array also. You also will probably also want to remove the ID part from these values, which my code does not do.
public class Split_ListwithIDs {
Hashtable<String, String[]> table = new Hashtable<String, String[]>();
Splitter spl ;
public Split_ListwithIDs(Splitter split){
spl = split;
}
private void addEntry(String key , String[] vals){
table.put(key, vals);
}
public void parseList(List<String[]> list){
for(String[] entry : list){
String[] temp = new String[entry.length - 1];
System.arraycopy(entry, 1, temp, 0,entry.length - 1);
addEntry(entry[0], spl.GetStringArrayOfNumbers(temp));
}
}
class SplittingHelper implements Splitter{
#Override
public String[] GetStringArrayOfNumbers(String[] arr) {
String[] strArray = null ;
// implementation here
return arr;
}
}
interface Splitter {
String[] GetStringArrayOfNumbers(String[] arr);
}
}
You will have to use a Hashtable instead of a list of objects.( I am assuming that you will need to search through the list for a given entry using the First alphabet as key - This will be very laborious if you want to use a List ).
In the method SplittingHelper , provide your custom logic to parse the string of numbers and return another string[] of numbers.
I don't understand your goal, but for 'an object with 2 parts' you might consider storing them in a Hashtable: http://download.oracle.com/javase/6/docs/api/java/util/Hashtable.html

proper way to use list to array?

public class TestClass{
private String divisions[] ={};
public void doAction(){
Collection testArray = new ArrayList();
// put testArray will data
divisions = (String [] ) testArray.toArray(division); //should i use this
divisions = (String [] ) testArray.toArray(new String [] {}); //should i use this?
}
}
if i use case 1, and i call doaction multiple time, the division, something will show wrong records
if i use case2, divisions will always show the correct records. is my assumption should use case 2?
Yes, in case 1 you could have a problem with extra items on the end of division. Example: the first time you called doAction and division was set to a certain length then if the next time you called it, it needed less space, there would be extra items that did not get overwritten in the array.
However, case 2 is not all that useful because if the array you pass in (which has a length of zero in your example) is not large enough, ArrayList will just create a new array anyway.
Case 2 is the "more correct" way to use it.
Essentially, you're telling the method what type you would like the resultant array.
Prefer the second one only
divisions = (String [] ) testArray.toArray(new String [] {});

Categories

Resources