I was wondering if you could help me with this problem, I'm stuck for a day in trying to solve this one. So basically what I want to do is have a list that will contain an array of an array.
I have this initialization
List<double[][]> points = new ArrayList<double[][]>();
I add the elements this way:
points.add(existing.Foods);
My beeColony class contains the data that I want to add:
public class beeColony{
double Foods[][]=new double[FoodNumber][D];
....
}
And here's how I declare an instance of it:
public beeColony existing=new beeColony();
Here's a snippet of the code:
for(run=0;run<existing.runtime;run++)
{
for (iter=0;iter<existing.maxCycle;iter++)
points.add(existing.Foods);
}
What happens is that when I output all the items the list, it only contains the last added items.
for example:
Foods = {(0,0), (1,1), (2,2), (3,3)}
points.add(Foods);
Foods = {(4,4), (5,5), (6,6), (7,7)}
points.add(Foods);
The way that I understand it is that
points.get(0)[0] should countain 0,0 and so on and points.get(1)[0] should contain 4,4 and so on. But what happens is points.get(0) also has the same values as points.get(1)
Collections like ArrayList<X> contain references to X objects, like one end of a string the other end of which is "tied" to the object itself, i.e., where the data resides.
This is also true for arrays like double[][].
What you do is to copy and store the reference end repeatedly, but at the other end there is one and the same double[][]. You can change the contents of that array, but all stored string ends lead to the same array object.
You must create new copies of that array to hold different array values. If you create another BeeColony, it will have another foods array. Otherwise, use new double[m][n] and copy the values. This is how:
double[][] d = { {1,2}, {3,4}, {5,6} };
// create the vector of (still missing) rows:
double[][] copy = new double[d.length][];
for( int row = 0; row < d.length; ++row ){
// create another row of appropriate length:
copy[row] = new double[d[row].length];
// copy the element values
System.arraycopy( d[row], 0, copy[row], 0, d[row].length );
}
PS: You should stick to Java conventions. Classe names are written in camel case starting with an upper case letter; variables and methods should start with a lower case letter. Loops should declare the loop counter inside the for: for( int run = 0;... ). Avoid public for class fields; code getters and setters to access private class fields.
You could use combination of array and iterator to get the work done,
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Random;
public class listerr {
static int getrandom(){
Random r = new Random();
int next = r.nextInt(100);
return next;
}
static double[][] getarr(){
double[][] arr = {{getrandom(),getrandom()}, {getrandom(),getrandom()},
{getrandom(),getrandom()}, {getrandom(),getrandom()}};
return arr;
}
public static void main(String[] args) {
List<double[][]> points = new ArrayList<double[][]>();
for(int run=0;run<3;run++)
{
double[][] arr = getarr();
points.add(arr);
}
Iterator itr = points.iterator();
while(itr.hasNext()){
double[][] dbl = (double[][]) itr.next();
for (int i=0;i<4;i++)
{ for (int j=0;j<2;j++){
System.out.println(dbl[i][j]);
}
}
}
}
}
Related
I am working on the first part of a String permutation problem and I am just looping over the first char of a string and swap it with every following char of that same String. I initialized an empty ArrayList to store all of those permutations called listeFinale. When I am printing that ArrayList, I am getting a collection of object and not values ([[C#61bbe9ba, [C#61bbe9ba, [C#61bbe9ba, [C#61bbe9ba]), how can I print each char stored in the ArrayList?
import java.util.ArrayList;
import java.util.List;
public class checkPermu {
public static void main(String[] args) {
String myString = "aabc";
applyPermu(myString);
}
public static void applyPermu(String toCheck){
char[] newString = toCheck.toCharArray();
List listeFinale = new ArrayList();
for(int i = 0 ; i < newString.length ; i ++){
char temp = newString[0];
newString[0] = newString[i];
newString[i] = temp;
listeFinale.add(newString);
System.out.println(listeFinale);
}
}
}
First of all, don't use raw types for your List please.. Change:
List listeFinale = new ArrayList();
to:
List<char[]> listeFinale = new ArrayList<>();
As for your actual problem. Those values you see are the default toString() outputs of your inner character-arrays. You could iterate over your list, and call the java.util.Arrays.toString(char[]) method for them like this:
listeFinale.forEach(arr -> System.out.println(Arrays.toString(arr)));
Or, if you want to print them back as String again, use new String(char[]):
listeFinale.forEach(arr -> System.out.println(new String(arr)));
Try it online.
I am trying to iterate through many arrays, two at a time. They contain upwards of ten-thousand entries each, including the source. In which I am trying to assign each word to either a noun, verb, adjective, or adverb.
I can't seem to figure a way to compare two arrays without writing an if else statement thousands of times.
I searched on Google and SO for similar issues. I couldn't find anything to move me forward.
package wcs;
import dictionaryReader.dicReader;
import sourceReader.sourceReader;
public class Assigner {
private static String source[], snArray[], svArray[], sadvArray[], sadjArray[];
private static String nArray[], vArray[], advArray[], adjArray[];
private static boolean finished = false;
public static void sourceAssign() {
sourceReader srcRead = new sourceReader();
//dicReader dic = new dicReader();
String[] nArray = dicReader.getnArray(), vArray = dicReader.getvArray(), advArray = dicReader.getAdvArray(),
adjArray = dicReader.getAdjArray();
String source[] = srcRead.getSource();
// Noun Store
for (int i = 0; i < source.length; i++) {
if (source[i] == dicReader.getnArray()[i]) {
source[i] = dicReader.getnArray()[i];
}else{
}
}
// Verb Store
// Adverb Store
// Adjective Store
}
}
Basically this is a simpler way to get a list of items that are in both Lists
// construct a list of item for first list
List<String> firstList = new ArrayList<>(Arrays.asList(new String[0])); // add items
//this function will only keep items in `firstList` if the value is in both lists
firstList.retainAll(Arrays.asList(new String[0]));
// iterate to do your work
for(String val:firstList) {
}
I have a 2D Arraylist matrix like
ArrayList[][] table = new ArrayList[10][10];
table[0][0] = new ArrayList();
table[0][1].add(10);
table[1][0].add(20);
table[1][1].add(30);
System.out.println("Value="+table[1][0].get()); //error line
The error occurs in the System.out.println line.
how do I print the values of the arraylist matrix??
can anyone suggest me a method??
You seem to think you have a 2-D matrix of numbers, stored as an ArrayList. That is not what you have at all. Instead, you have a 2-D matrix where each element is an ArrayList. That means you really have 3 dimensions represented in your code. I don't think that's what you want. There are several ways you could achieve two dimensions using the constructs you already have (i.e. without going to some external library).
A 2-D array of numbers
The array is an easy to understand construct, so let's start with that.
Number[][] table = new Number[10][10];
table[0][0] = 0;
table[0][1] = 10;
table[1][0] = 20;
table[1][1] = 30;
System.out.println("Value="+table[1][0].get());
This code declares a 2-D array of type Number, then initializes it with 10 rows and 10 columns. It then partially fills in numbers. As long as you access an element that has already been initialized, you'll be ok. Trying to access an element that hasn't yet been initialized (like table[3][4]) would be bad.
Another way to initialize an array
Number[][] table = { { 0, 10 }, { 20, 30 } };
System.out.println("Value=" + table[1][0]);
This is the same thing as before, but initialized all at once. This particular array only has 2 rows and 2 columns.
Nested ArrayLists
If you want to use an ArrayList instead of an array, that's fine. You just need to realize that the ArrayList actually will contain other ArrayLists, each of which will contain Numbers. Like so:
ArrayList<ArrayList<Number>> table = new ArrayList<>();
table.add(new ArrayList<>());
table.add(new ArrayList<>());
table.get(0).add(0);
table.get(0).add(10);
table.get(1).add(20);
table.get(1).add(30);
System.out.println("Value=" + table.get(1).get(0));
In this example, you first declare an ArrayList that contains ArrayLists that contain Numbers, and initialize the outer ArrayList. Then you create some inner ArrayLists, and finally give each of them some Numbers.
Summary
You can use arrays or ArrayLists as you prefer. You just have to initialize them correctly before accessing their elements. How to initialize depends on the data structure you choose.
All the codes
import java.util.ArrayList;
public class TwoD {
public void example1() {
Number[][] table = new Number[10][10];
table[0][0] = 0;
table[0][1] = 10;
table[1][0] = 20;
table[1][1] = 30;
System.out.println("\nExample 1");
System.out.println("Value=" + table[1][0]);
}
public void example2() {
Number[][] table = { { 0, 10 }, { 20, 30 } };
System.out.println("\nExample 2");
System.out.println("Value=" + table[1][0]);
}
public void example3() {
ArrayList<ArrayList<Number>> table = new ArrayList<>();
table.add(new ArrayList<>());
table.add(new ArrayList<>());
table.get(0).add(0);
table.get(0).add(10);
table.get(1).add(20);
table.get(1).add(30);
System.out.println("\nExample 3");
System.out.println("Value=" + table.get(1).get(0));
}
public static void main(String[] args) {
TwoD me = new TwoD();
me.example1();
me.example2();
me.example3();
}
}
THe actual exception is at the lines
table[0][0] = new ArrayList();
table[0][1].add(10);
You are adding element at 0,0 position and trying to add the arraylist element at 0,1.
Hence the nullpointer.
Try
public static void main(String[] args) {
ArrayList[][] table = new ArrayList[10][10];
table[0][0] = new ArrayList();
table[0][0].add(10);
table[0][0].add(20);
table[0][0].add(30);
System.out.println("Value="+table[0][0].get(1));
}
For using ArrayList, you must first declare the type of ArrayList in angular braces. Try using the code snippet as below:
ArrayList<ArrayList<Integer>> table = new ArrayList<ArrayList<Integer>>(); //2d ArrayList
ArrayList<Integer> x = new ArrayList<Integer>();
x.add(10);
x.add(20);
table.add(x);
table.add(x);
System.out.println("Value="+table); //Prints table[][]
System.out.println("Value="+table.get(0)); //Prints table[0]
System.out.println("Value="+table.get(0).get(1)); //Prints table [0][1]
To insert a new row, you must do
table.add(new ArrayList<Integer>());
and to append another element on a specific row you must do
table.get(row).add(someValue);
If you are looking for something more than toy project you should seriously consider using some external matrix library. Arrays will be painful in maintenance.
I could recommend EJML. With usage of this library your code will look like this:
BlockMatrix64F matrix = new BlockMatrix64F(10, 10);
matrix.set(0,1,10);
matrix.set(1,0,20);
matrix.set(1,1,30);
System.out.println("Value="+matrix.get(1,0));
Additionally it is quite likely that you will have to make some calculations inside your matrix. Library will have some support for basic ones, and will save you some time.
I am trying to write a write a program that receives an String[] and prints out the array with the first string alphabetically first. I have to use three methods like these. Here is a sample input/output:
bob, joe, aaron, zack ----> aaron, bob, joe, zack
findFirstName() is correctly finding the first String alphabetically and returning its location.
MoveToRightOne is correctly shifting each String right one while overwriting the first string alphabetically and repeating the first one (ex: bob bob joe zack).
moveName() is not working correctly. It is supposed to replace the first instance of "bob" with "aaron" but is usually off by one or two places.
Does anyone see why this might be happening in moveOne()?
public static String [] moveName(String [] names) {
String names1 [] = names.clone();
int firstPosition = findFirstName(names1);
String[] NewNames = moveToRightOne(names1, firstPosition, firstPosition+1);
String firstAlph= names1 [firstPosition];
System.out.println(names1 [firstPosition]);
NewNames [0] = firstAlph;
return NewNames;
}
public static int findFirstName(String[ ] names1 ) {
// receives an array of Strings, and returns the location (i.e. index) of the first
// name (alphabetically)
String first=names1[0];
int firstPosition = 0;
for (int i=0; i<names1.length; i++) {
int result =names1[i].compareToIgnoreCase(first);
if (result < 0) {
first= names1[i];
firstPosition = i;
}
}
return firstPosition;
}
public static String[] moveToRightOne (String[] names, int startSpot, int endSpot) {
for (int i = (startSpot - 1); i >= 0; i--) {
names[i+1] = names[i];
}
return names;
}
moveToRightOne does not make a copy of the names array that you pass in. Instead, it modifies it directly. That means when you say
String[] NewNames = moveToRightOne(names1, firstPosition, firstPosition+1);
the strings will be shifted in names1, and after that, NewNames and names1 will just be references to the same array. I think your intent is to make NewNames be an array with the strings shifted, and leave names1 alone, but that isn't what's happening. That means that the following statement is going to return the wrong string:
String firstAlph= names1 [firstPosition];
(Or, since names1 is already a clone of names, maybe what you want is to use names instead of names1 when trying to access elements from the not-yet-shifted array.)
Your moveToRightOne function was broken, so you were not actually using all the parameters passed in. Also, you should grab the first name alphabetically before you actually overwrite it using that function.
public class Shift {
public static void moveName(String [] names) {
int firstPosition = findFirstName(names);
// Store the name at that position
String firstName = names[firstPosition];
moveToRightOne(names, 0, firstPosition);
names [0] = firstName;
}
public static int findFirstName(String[] names1) {
// receives an array of Strings, and returns the location (i.e. index)
// of the first name (alphabetically)
String first=names1[0];
int firstPosition = 0;
for (int i=0; i<names1.length; i++) {
int result =names1[i].compareToIgnoreCase(first);
if (result < 0) {
first= names1[i];
firstPosition = i;
}
}
return firstPosition;
}
public static void moveToRightOne (String[] names, int startSpot, int endSpot) {
for (int i = (endSpot - 1); i >= startSpot; i--) {
names[i+1] = names[i];
}
}
public static void main(String[] args) {
String[] original = new String[] { "bob", "joe", "aaron", "zac"};
for (String s: original) System.out.println(s);
System.out.println();
moveName(original);
for (String s: original) System.out.println(s);
}
}
Are you sure the moveToRightOne is correct? (if firstPosition is 0 you will get no changes as the for loop will not execute)
Just a quick Thought:
If you are looking do a sort manually (I assume this is for a class). I will also assume you are trying to implement insertion sort algorithm (otherwise Arrays.sort() is your friend). The way you are approaching it, it looks like you will be making multiple passes through the array to achieve a sort. if you want to do that switch to bubble sort instead.
The description of the insertion sort code will look something like this:
Start looping through your array, compare that the element at index is greater than element at index + 1. if not true move to the next element. if true compare the smaller element (call it A) to all previous elements until it is greater than the next previous element (lets call it B). Save a copy of A Shift all elements after B to the right (by 1) until you get to the A's old position . insert the copy of A into position just after B. Continue from the old A's index. Rinse/repeat until the end of the array
you may want to simplify your code in that case (and always check for edge conditions like 0 and Array.length)
HTH
Please use Arrays.sort() for sorting instead.This is not exact solution for the problem, but an alternate way for it.
import java.util.Arrays;
public class Test{
Public static void main(String args[]){
String str[]= {'Mike','Adam','Peter','Brian'};
System.out.println("str"+str[0]); // Mike
Arrays.sort(str);
System.out.println("str"+str[0]); //Adam
}
}
I am trying to write a method that takes an ArrayList of Strings as a parameter and that places a string of four asterisks in front of every string of length 4.
However, in my code, I am getting an error in the way I constructed my method.
Here is my mark length class
import java.util.ArrayList;
public class Marklength {
void marklength4(ArrayList <String> themarklength){
for(String n : themarklength){
if(n.length() ==4){
themarklength.add("****");
}
}
System.out.println(themarklength);
}
}
And the following is my main class:
import java.util.ArrayList;
public class MarklengthTestDrive {
public static void main(String[] args){
ArrayList <String> words = new ArrayList<String>();
words.add("Kane");
words.add("Cane");
words.add("Fame");
words.add("Dame");
words.add("Lame");
words.add("Same");
Marklength ish = new Marklength();
ish.marklength4(words);
}
}
Essentially in this case, it should run so it adds an arraylist with a string of "****" placed before every previous element of the array list because the lengths of the strings are all 4.
BTW
This consists of adding another element
I am not sure where I went wrong. Possibly in my for loop?
I got the following error:
Exception in thread "main" java.util.ConcurrentModificationException
at java.util.AbstractList$Itr.checkForComodification(AbstractList.java:372)
at java.util.AbstractList$Itr.next(AbstractList.java:343)
at Marklength.marklength4(Marklength.java:7)
at MarklengthTestDrive.main(MarklengthTestDrive.java:18)
Thank you very much. Help is appreciated.
Let's think about this piece of code, and pretend like you don't get that exception:
import java.util.ArrayList;
public class Marklength {
void marklength4(ArrayList <String> themarklength){
for(String n : themarklength){
if(n.length() ==4){
themarklength.add("****");
}
}
System.out.println(themarklength);
}
}
Ok, so what happens if your list just contains item.
You hit the line if(n.length() ==4){, which is true because you are looking at item, so you go execute its block.
Next you hit the line themarklength.add("****");. Your list now has the element **** at the end of it.
The loop continues, and you get the next item in the list, which happens to be the one you just added, ****.
The next line you hit is if(n.length() ==4){. This is true, so you execute its block.
You go to the line themarklength.add("****");, and add **** to the end of the list.
Do we see a bad pattern here? Yes, yes we do.
The Java runtime environment also knows that this is bad, which is why it prevents something called Concurrent Modification. In your case, this means you cannot modify a list while you are iterating over it, which is what that for loop does.
My best guess as to what you are trying to do is something like this:
import java.util.ArrayList;
public class Marklength {
ArrayList<String> marklength4(ArrayList <String> themarklength){
ArrayList<String> markedStrings = new ArrayList<String>(themarklength.size());
for(String n : themarklength){
if(n.length() ==4){
markedStrings.add("****");
}
markedStrings.add(n);
}
System.out.println(themarklength);
return markedStrings;
}
}
And then:
import java.util.ArrayList;
public class MarklengthTestDrive {
public static void main(String[] args){
ArrayList <String> words = new ArrayList<String>();
words.add("Kane");
words.add("Cane");
words.add("Fame");
words.add("Dame");
words.add("Lame");
words.add("Same");
Marklength ish = new Marklength();
words = ish.marklength4(words);
}
}
This...
if(n.length() ==4){
themarklength.add("****");
}
Is simply trying to add "****" to the end of the list. This fails because the Iterator used by the for-each loop won't allow changes to occur to the underlying List while it's been iterated.
You could create a copy of the List first...
List<String> values = new ArrayList<String>(themarklength);
Or convert it to an array of String
String[] values = themarklength.toArray(new String[themarklength.size()]);
And uses these as you iteration points...
for (String value : values) {
Next, you need to be able to insert a new element into the ArrayList at a specific point. To do this, you will need to know the original index of the value you are working with...
if (value.length() == 4) {
int index = themarklength.indexOf(value);
And then add a new value at the required location...
themarklength.add(index, "****");
This will add the "****" at the index point, pushing all the other entries down
Updated
As has, correctly, been pointed out to me, the use of themarklength.indexOf(value) won't take into account the use case where the themarklength list contains two elements of the same value, which would return the wrong index.
I also wasn't focusing on performance as a major requirement for the providing a possible solution.
Updated...
As pointed out by JohnGarnder and AnthonyAccioly, you could use for-loop instead of a for-each which would allow you to dispense with the themarklength.indexOf(value)
This will remove the risk of duplicate values messing up the index location and improve the overall performance, as you don't need to create a second iterator...
// This assumes you're using the ArrayList as the copy...
for (int index = 0; index < themarklength.size(); index++) {
String value = themarklength.get(index);
if (value.length() == 4) {
themarklength.add(index, "****");
index++;
But which you use is up to you...
The problem is that in your method, you didn't modify each string in the arraylist, but only adds 4 stars to the list. So the correct way to do this is, you need to modify each element of the arraylist and replace the old string with the new one:
void marklength4(ArrayList<String> themarklength){
int index = 0;
for(String n : themarklength){
if(n.length() ==4){
n = "****" + n;
}
themarklength.set(index++, n);
}
System.out.println(themarklength);
}
If this is not what you want but you want to add a new string "**" before each element in the arraylist, then you can use listIterator method in the ArrayList to add new additional element before EACH string if the length is 4.
ListIterator<String> it = themarklength.listIterator();
while(it.hasNext()) {
String name = it.next();
if(name.length() == 4) {
it.previous();
it.add("****");
it.next();
}
}
The difference is: ListIterator allows you to modify the list when iterating through it and also allows you to go backward in the list.
I would use a ListIterator instead of a for each, listiterator.add likely do exactly what you want.
public void marklength4(List<String> themarklength){
final ListIterator<String> lit =
themarklength.listIterator(themarklength.size());
boolean shouldInsert = false;
while(lit.hasPrevious()) {
if (shouldInsert) {
lit.add("****");
lit.previous();
shouldInsert = false;
}
final String n = lit.previous();
shouldInsert = (n.length() == 4);
}
if (shouldInsert) {
lit.add("****");
}
}
Working example
Oh I remember this lovely error from the good old days. The problem is that your ArrayList isn't completely populated by the time the array element is to be accessed. Think of it, you create the object and then immediately start looping it. The object hence, has to populate itself with the values as the loop is going to be running.
The simple way to solve this is to pre-populate your ArrayList.
public class MarklengthTestDrive {
public static void main(String[] args){
ArrayList <String> words = new ArrayList<String>() {{
words.add("Kane");
words.add("Cane");
words.add("Fame");
words.add("Dame");
words.add("Lame");
words.add("Same");
}};
}
}
Do tell me if that fixes it. You can also use a static initializer.
make temporary arraylist, modify this list and copy its content at the end to the original list
import java.util.ArrayList;
public class MarkLength {
void marklength4(ArrayList <String> themarklength){
ArrayList<String> temp = new ArrayList<String>();
for(String n : themarklength){
if(n.length() ==4){
temp.add(n);
temp.add("****");
}
}
themarklength.clear();
themarklength.addAll(temp);
System.out.println(themarklength);
}
}