Reverse order of the Arrays stored in ArrayList - java

I'm working with Processing and IGeo library and I have an ArrayList of IVec[] arrays:
ArrayList<IVec []> v = new ArrayList<IVec[]>();
For every I of the ArrayList I have a collection of IVec [] arrays that represent the coordinates of the control points of a curve. I need to reverse the order of the IVec [] control points keeping the same order of the ArrayList (I'm trying to invert curve seam reversing control points order and keeping the original order of the curves) but I can't understand how to do this.
Can anyone help me?

I won't provide you a full solution, but will guide you through it:
Iterate on the array list v
for each item in it (IVec[]),
Convert the array to a collection (for example using Arrays.asList)
Use Collections.reverse to reverse the items in the list
Conver it back to an array

You can use Collections.reverse
You can also use a stack data structure. You can iterate over collection you wish to reverse by pushing the elements into the stack. Then, when you actually want to use the elements, you pop each element from the stack, which will allow you to iterate over the collection in reverse order.

This solution is working:
for (int i=0; i<v.size (); i++) {
IVec [] vert=v.get(i);
for (int j=0; j<vert.length/2; j++) {
IVec temp = vert[j];
vert[j]=vert[vert.length -1 - j];
vert[vert.length - 1 - j] = temp;
}
}

Try this;
Create a Helper method/function that takes and returns array.
Inside the Helper method, use Collections.reverse
return the reversed array.
call this helper method inside a loop as below:
for(int i = 0; i < OutArray.length; I++)
{ // Here get the inner Array and pass it to Helper method.
// Add the return array to newArray List
}
return newArrayList.

This should work (not the most efficient way, but easily understood):
public static <T> void reverseElements(ArrayList<T[]> list) {
ArrayList<T> tempList = new ArrayList<T>();
for(T[] arr : list) {
tempList.clear();
for(T t : arr)
tempList.add(t);
Collections.reverse(tempList);
tempList.toArray(arr);
arr = tempList.toArray(arr);
}
}

Related

go through an array of linked lists

I want to create an array of pointers to linked lists and then go through each list. To create it can I simply create however many lists I need and then just do something like
LinkedList array[] = new LinkedList[length];
and then just set a loop to set each value in the array to point to one of the lists?
How would I go through each list after I set it all up? I thought it was something like
while(array[x].hasNext()){
//do stuff
x++;
}
your while loop is incorrect:
Just do something like this!
for (LinkedList list : array) {
for (Item object : list) {
// Do something here with the item
}
}
btw you should not use LinkedList without a type, use one of the following
LinkedList<String> or
LinkedList<WhateverObjectYouLike> or
LinkedList<? extends whatEverObjectYouLike>
so lets say you want to create an array of 10 lists and every list should contain strings.
LinkedList<String> array[] = new LinkedList<String>[10];
for (int i=0; i<10; i++) {
array[i] = new LinkedList<String>();
}
// Add some strings to each list, as you like
...
// Print all added Strings:
for (LinkedList<String> list : array) {
for (String item : list) {
System.out.println(item);
}
}
You have mixed up Java array objects and the collection framework's List api. You can do what you want in a couple of ways:
Using arrays (highly discouraged—see this thread):
LinkedList array[] = new LinkedList[length];
...
for (int i = 0; i < array.length; ++i) {
LinkedList list = array[i];
// do stuff with list
}
Using a List:
List<LinkedList> array = new ArrayList<LinkedList>();
...
for (Iterator<LinkedList> iter = array.iterator();
iter.hasNext();
)
{
LinkedList list = iter.next();
// do stuff with list
}
In both cases, you might benefit from using an enhanced for loop:
for (LinkedList list : array) {
// do stuff with list
}
This works for either the array-based or List-based versions.
P.S. You should not be using raw LinkedList types. Instead, you should bind the generic type parameter of LinkedList to a specific element type (even if it's Object). For example:
List<LinkedList<String>> array = new ArrayList<LinkedList<String>>();
The language allows raw types for the sake of old code, but new code should never use them. However, the first option above will not work—you will have to use the second approach.

How to make ArrayList that work as two dimentional array in java?

I want to make arrayList object in java that work as two dimentional array. My question is how can we access value from specific dimention from arrayList.
in two dimentional array, if i want to access value then it can be as m[i][j].
But in arraylist how can i do that ?
You mean something like a List in a List??
May be something like...
List<List<...>> twoDList = new ArrayList<>();
i want to make a List, in which each List key contains another List inside it
It should more like you want some kind of Map, which is basically a key/value pair.
Map<String, List<String>> mapValues = new HashMap<>(25);
List<String> listOfValues = ...;
//...
mapValues.put("A unique key for this list", listOfValues);
//...
List<String> thatListOfValues = mapValues.get("A unique key for this list");
List<List<Integer>> list = new ArrayList<List<Integer>>();
list.add(new ArrayList<Integer>());
list.add(new ArrayList<Integer>());
list.get(0).add(5);
list.get(1).add(6);
for(List<Integer> listiter : list)
{
for(Integer integer : listiter)
{
System.out.println("" + integer);
}
}
This way you can get the items like
list.get(1).get(0); //second dimension list -> integer
EDIT:
Although it is true that you can use a Map if you are trying to use numeric indices for example for each list, like so:
Map<Integer, List<YourObject>> map = new HashMap<Integer, List<YourObject>>();
map.put(0, new ArrayList<YourObject>());
map.put(5, new ArrayList<YourObject>());
map.get(0).add(new YourObject("Hello"));
map.get(5).add(new YourObject("World"));
for(Integer integer : map.keySet())
{
for(YourObject yourObject : map.get(integer))
{
yourObject.print(); //example method
System.out.println(" ");
}
}
Although even then the accessing of Lists would be the same as before,
map.get(0).get(1); //List -> value at index
Obviously you don't need to use Integers as the generic type parameter, that's just a placeholder type.
The solution like List<List<..>> is slow then you should use one dimention array like
// Two dimentions: m and n
List<String> arr = new ArrayList<String>(m*n);
for (int i=0; i< m; ++i) {
for (int j=0; j<n; ++j) {
String str=arr.get(i*n + j);
//You code here
}
}
Memory is an important consideration here.
It can be acceptable to model a 2D (or higher dimension) array using a 1D container. (This is how the VARIANT SAFEARRAY of Microsoft's COM works.) But, consider this carefully if the number of elements is large; especially if the container allocates a contiguous memory block. Using something like List<List<... will model a jagged-edged matrix and can fragment your memory.
With the 1D approach, you can use the get(index) method on the ArrayList appropriately transformed:
Given the (i)th row and (j)th column, transform using index = i * rows + j where rows is the number of rows in your matrix.
An arraylist is not an object to make a 2 dimentional arrays. However you can use it anyway :
You can use :
new ArrayList<ArrayList<Object>>; //or
new ArrayList<Object[]>;
But you should implement your own matrix class because you will probably have some check to do and a function get(int row, int column) would be cool
Also consider Table collection provided by Google Guava library. ArrayTable is an implementation based on 2D array.
You cane define like this
1>
List<Object[]> list = new ArrayList<Object[]>();
Fetching
list.get(i)[j];
2>
List<Map<Integer,Object>> list = new ArrayList<Map<Integer,Object>>();
Fetching
list.get(i).get(j);

Given a String array, how to create a second array which is a rearrangement of the original?

I am trying to create a method to takes an array of names and returns a copy of the list with the names randomly rearranged. The code below returns a new list with duplicated names. what can I do to shuffle names of the new list instead?
public static String[] shuffle(String []names)
{
int num =0;
String [] newArray = new String [names.length];
Random r = new Random ();
for(int i = 0; i<names.length; i++){
num = r.nextInt(names.length);
if((i-1)!=num){
newArray[i]=names[num];
}
}
return newArray;
}
You can use Collections.shuffle() to shuffle a list.
If you are eager to do it by your own - have a look on fisher-yates shuffle.
(Pseudo code:)
for (i = n-1; i >= 0; i--)
swap(names,i,r.nextInt(i+1));
(Where swap() is a standard swapping function to swap two elements in an array)
(Note, if you want a new instance with the shuffled array - just copy it using Arrays.copyOf() before running the algorithm.
Like others have suggested there are already other cleaver/easy ways to do this, but to solve the issue in your code you need to make the newArray a copy of the names array (you can can use Arrays.copyOf) and then properly swap the values, like:
if(i!=num){
String aux=newArray[i];
newArray[i]=newArray[num];
newArray[num]=aux;
}
Collections.shuffle(list)
Info
You can use the ToList to make it a list for the shuffle and then back to an array with ToArray.
This may not be the most efficient but it is the easiest.
public String[] shuffle(String[] ss) {
List<String> list = Collections.shuffle(Arrays.asList(ss));
return list.toArray(new String[ss.length]);
}

How to sort an ArrayList

All I need is the simplest method of sorting an ArrayList that does not use the in-built Java sorter. Currently I change my ArrayList to an Array and use a liner sorting code, but I later need to call on some elements and ArrayLists are easier to do that.
you can use anonymous sort.
Collections.sort(<ArrayList name>, Comparator<T>() {
public int compare(T o1, T o2) {
.....
....
}
});
where T is the type you want to sort (i.e String, Objects)
and simply implement the Comparator interface to your own needs
Assuming an ArrayList<String> a...
Easiest (but I'm guessing this is what you're saying you can't use):
Collections.sort(a);
Next easiest (but a waste):
a = new ArrayList<String>(new TreeSet<String>(a));
Assuming "in-built sort" refers to Collections.sort() and you are fine with the sorting algorithm you have implemented, you can just convert your sorted array into an ArrayList
ArrayList list = new ArrayList(Arrays.asList(sortedArray));
Alternatively, you can rewrite your sorting algorithm to work with a List (such as an ArrayList) instead of an array by using the get(int index) and set(int index, E element) methods.
Sorting Arguments passed through Command prompt; without using Arrays.sort
public class Sort {
public static void main(String args[])
{
for(int j = 0; j < args.length; j++)
{
for(int i = j + 1; i < args.length; i++)
{
if(args[i].compareTo(args[j]) < 0)
{
String t = args[j];
args[j] = args[i];
args[i] = t;
}
}
System.out.println(args[j]);
}
}
}
By using Array.sort
import java.util.*;
public class IntegerArray {
public static void main(String args[])
{
int[] num=new int[]{10, 15, 20, 25, 12, 14};
Arrays.sort(num);
System.out.println("Ascending order: ");
for (int i=0; i<num.length; i++)
System.out.print(num[i] + " ");
}
}
Collections.sort(List);
If i remember correctly when you pull an element out of the middle of an arrayList it moves the rest of the elements down automaticly. If you do a loop that looks for the lowest value and pull it out then place it at the end of the arrayList. On each pass i-- for the index. That is use one less. So on a 10 element list you will look at all 10 elements take the lowest one and append it to the end. Then you will look at the first nine and take the lowest of it out and append it to the end. Then the first 8 and so on till the list is sorted.
Check for Comparator in java. You can implement your own sorting using this and use Collections.sort(..) to sort the arraylist using your own Comparator
If you are meant to sort the array yourself, then one of the simplest algorithms is bubble sort. This works by making multiple passes through the array, comparing adjacent pairs of elements, and swapping them if the left one is larger than the right one.
Since this is homework, I'll leave it to you to figure out the rest. Start by visualizing your algorithm, then think about how many passes your algorithm needs to make, and where it needs to start each pass. Then code it.
You also need to understand and solve the problem of how you compare a pair of array elements:
If the elements are instances of a primitive type, you just use a relational operator.
If the elements are instances of reference types, you'll need to use either the Comparable or Comparator interface. Look them up in the javadocs. (And looking them up is part of your homework ...)
Here is a "simple" quicksort implementation:
public Comparable<Object>[] quickSort(Comparable<Object>[] array) {
if (array.length <= 1) {
return array;
}
List<Comparable<Object>> less = new ArrayList<Comparable<Object>>();
List<Comparable<Object>> greater = new ArrayList<Comparable<Object>>();
Comparable<Object> pivot = array[array.length / 2];
for (int i = 0;i < array.length;i++) {
if (array[i].equals(pivot)) {
continue;
}
if (array[i].compareTo(pivot) <= 0) {
less.add(array[i]);
} else {
greater.add(array[i]);
}
}
List<Comparable<Object>> result = new ArrayList<Comparable<Object>>(array.length);
result.addAll(Arrays.asList(quickSort(less.toArray(new Comparable<Object>[less.size()]))));
result.add(pivot);
result.addAll(Arrays.asList(quickSort(greater.toArray(new Comparable<Object>[greater.size()]))));
return result.toArray(new Comparable<Object>[result.size()]);
}
The last operations with arrays and list to build the result can be enhanced using System.arraycopy.

How can I dynamically add items to a Java array?

In PHP, you can dynamically add elements to arrays by the following:
$x = new Array();
$x[] = 1;
$x[] = 2;
After this, $x would be an array like this: {1,2}.
Is there a way to do something similar in Java?
Look at java.util.LinkedList or java.util.ArrayList
List<Integer> x = new ArrayList<Integer>();
x.add(1);
x.add(2);
Arrays in Java have a fixed size, so you can't "add something at the end" as you could do in PHP.
A bit similar to the PHP behaviour is this:
int[] addElement(int[] org, int added) {
int[] result = Arrays.copyOf(org, org.length +1);
result[org.length] = added;
return result;
}
Then you can write:
x = new int[0];
x = addElement(x, 1);
x = addElement(x, 2);
System.out.println(Arrays.toString(x));
But this scheme is horribly inefficient for larger arrays, as it makes a copy of the whole array each time. (And it is in fact not completely equivalent to PHP, since your old arrays stays the same).
The PHP arrays are in fact quite the same as a Java HashMap with an added "max key", so it would know which key to use next, and a strange iteration order (and a strange equivalence relation between Integer keys and some Strings). But for simple indexed collections, better use a List in Java, like the other answerers proposed.
If you want to avoid using List because of the overhead of wrapping every int in an Integer, consider using reimplementations of collections for primitive types, which use arrays internally, but will not do a copy on every change, only when the internal array is full (just like ArrayList). (One quickly googled example is this IntList class.)
Guava contains methods creating such wrappers in Ints.asList, Longs.asList, etc.
Apache Commons has an ArrayUtils implementation to add an element at the end of the new array:
/** Copies the given array and adds the given element at the end of the new array. */
public static <T> T[] add(T[] array, T element)
I have seen this question very often in the web and in my opinion, many people with high reputation did not answer these questions properly. So I would like to express my own answer here.
First we should consider there is a difference between array and arraylist.
The question asks for adding an element to an array, and not ArrayList
The answer is quite simple. It can be done in 3 steps.
Convert array to an arraylist
Add element to the arrayList
Convert back the new arrayList to the array
Here is the simple picture of it
And finally here is the code:
Step 1:
public List<String> convertArrayToList(String[] array){
List<String> stringList = new ArrayList<String>(Arrays.asList(array));
return stringList;
}
Step 2:
public List<String> addToList(String element,List<String> list){
list.add(element);
return list;
}
Step 3:
public String[] convertListToArray(List<String> list){
String[] ins = (String[])list.toArray(new String[list.size()]);
return ins;
}
Step 4
public String[] addNewItemToArray(String element,String [] array){
List<String> list = convertArrayToList(array);
list= addToList(element,list);
return convertListToArray(list);
}
You can use an ArrayList and then use the toArray() method. But depending on what you are doing, you might not even need an array at all. Look into seeing if Lists are more what you want.
See: Java List Tutorial
You probably want to use an ArrayList for this -- for a dynamically sized array like structure.
You can dynamically add elements to an array using Collection Frameworks in JAVA. collection Framework doesn't work on primitive data types.
This Collection framework will be available in "java.util.*" package
For example if you use ArrayList,
Create an object to it and then add number of elements (any type like String, Integer ...etc)
ArrayList a = new ArrayList();
a.add("suman");
a.add(new Integer(3));
a.add("gurram");
Now you were added 3 elements to an array.
if you want to remove any of added elements
a.remove("suman");
again if you want to add any element
a.add("Gurram");
So the array size is incresing / decreasing dynamically..
Use an ArrayList or juggle to arrays to auto increment the array size.
keep a count of where you are in the primitive array
class recordStuff extends Thread
{
double[] aListOfDoubles;
int i = 0;
void run()
{
double newData;
newData = getNewData(); // gets data from somewhere
aListofDoubles[i] = newData; // adds it to the primitive array of doubles
i++ // increments the counter for the next pass
System.out.println("mode: " + doStuff());
}
void doStuff()
{
// Calculate the mode of the double[] array
for (int i = 0; i < aListOfDoubles.length; i++)
{
int count = 0;
for (int j = 0; j < aListOfDoubles.length; j++)
{
if (a[j] == a[i]) count++;
}
if (count > maxCount)
{
maxCount = count;
maxValue = aListOfDoubles[i];
}
}
return maxValue;
}
}
This is a simple way to add to an array in java. I used a second array to store my original array, and then added one more element to it. After that I passed that array back to the original one.
int [] test = {12,22,33};
int [] test2= new int[test.length+1];
int m=5;int mz=0;
for ( int test3: test)
{
test2[mz]=test3; mz++;
}
test2[mz++]=m;
test=test2;
for ( int test3: test)
{
System.out.println(test3);
}
In Java size of array is fixed , but you can add elements dynamically to a fixed sized array using its index and for loop. Please find example below.
package simplejava;
import java.util.Arrays;
/**
*
* #author sashant
*/
public class SimpleJava {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
try{
String[] transactions;
transactions = new String[10];
for(int i = 0; i < transactions.length; i++){
transactions[i] = "transaction - "+Integer.toString(i);
}
System.out.println(Arrays.toString(transactions));
}catch(Exception exc){
System.out.println(exc.getMessage());
System.out.println(Arrays.toString(exc.getStackTrace()));
}
}
}

Categories

Resources