I'm making a program where it takes a list of elements in an arraylist and using recursion, gets the even and odd elements. For instance, if it were {1,2,3,4,5,6}. It would return {1,3,5} because they have an even element placement.
I figured out how to do it for even numbers without a hitch, but I can't seem to make it work for odds.
Here is the error:
java.lang.ArrayIndexOutofBoundsException:
-1 (in java.util.ArrayList)
Here is my even code:
public static ArrayList<Integer> even(ArrayList<Integer> tList)
{
ArrayList<Integer> newList = ListMethods.deepClone(tList);
int temp = newList.size();
if (newList.size()<=0)// The list is empty or has one element)
{
return newList;// Return the list as is – no need to reverse!
}
else
{
if(newList.size()%2==0)
temp = newList.remove(newList.size()-2);
newList.remove(newList.size()-1);
newList = ListMethods.even(newList);
if (temp!=0)
newList.add(temp);
}
return newList;
}
Odd Code: (this is where I get the error)
public static ArrayList<Integer> odd(ArrayList<Integer> tList)
{
ArrayList<Integer> newList = ListMethods.deepClone(tList);
int temp = newList.size();
if (newList.size()<=0)// The list is empty or has one element)
{
return newList;// Return the list as is – no need to reverse!
}
else
{
if(newList.size()%2==1)
temp = newList.remove(newList.size()-1);
newList.remove(newList.size()-1);
newList = ListMethods.odd(newList);
if (temp!=0)
newList.add(temp);
}
return newList;
}
Deep Clone:
public static ArrayList<Integer> deepClone(ArrayList<Integer> tList)
{
ArrayList<Integer> list = new ArrayList<Integer>();
for (Integer i : tList)
{
list.add(new Integer(i));
}
return list;
}
My Tester Code:
import java.util.ArrayList;
import java.util.Scanner;
public class ListMethodsRunner
{
public static void main(String[] args)
{
ArrayList<Integer> tempList = ListMethods.makeList(100);
System.out.println("What would you like to do to this ArrayList? Type the number.");
System.out.println("1. Show Even Elements");
System.out.println("2. Show Odd Elements");
System.out.println(" ");
Scanner input = new Scanner(System.in);
int z = input.nextInt();
if(z==1)
tempList = ListMethods.even(tempList);
if(z==2)
tempList = ListMethods.odd(tempList);
if (tempList.size() == 0)
{
System.out.println("The list is empty");
}
else
{
for (Integer i : tempList)
{
System.out.println(i);
}
}
}
}
Nevermind guys, I figured it out by myself.
public static ArrayList<Integer> odd(ArrayList<Integer> tList)
{
ArrayList<Integer> newList = ListMethods.deepClone(tList);
int temp = newList.size();
if (newList.size()<=0)// The list is empty or has one element)
{
return newList;// Return the list as is – no need to reverse!
}
else
{
if(newList.size()%2==0) // I had `1` here instead of `0`
temp = newList.remove(newList.size()-1);
newList.remove(newList.size()-1);
newList = ListMethods.odd(newList);
if (temp!=0)
newList.add(temp);
}
return newList;
I am not sure if the above code will work in case you have odd number of entries May be you can use something like below :
public static ArrayList<Integer> returnList(ArrayList<Integer> tList,boolean flag){
int size=tList.size();
int t;
//print odd positions - flag is true
if(flag){
if(size>0 && size%2==0){
t = tList.remove(size-1);
tList=returnList(tList,flag);
tList.add(t);
}
else if(size%2 == 1){
t = tList.remove(size-1);
tList=returnList(tList,flag);
}
else{
}
System.out.println("Printing.."+tList);
}
else{
}
return tList;
}
Related
I tried taking input in ArrayList but it shows out of memory. can anybody see whats wrong?
first i created takeInput to receive input till last number entered is -1. After that i made print function to print the code
Code-
import java.util.*;
public class ArrayListTakeInput {
/**
* #return
*/
public static ArrayList<Integer> takeInput(){
ArrayList<Integer> list = new ArrayList<Integer>();
Scanner s=new Scanner(System.in);
int i=s.nextInt();
while(i!=-1){
list.add(i);
}
return list;
}
public static void print(ArrayList<Integer> list2){
for(int i=0; i<list2.size(); i++) {
System.out.print(list2.get(i) + " ");
}
}
public static void main(String[] args) {
ArrayList<Integer> list2 = new ArrayList<Integer>();
list2=takeInput();
print(list2);
}
}
The problem is your condition of your while loop in the method takeInput(). Your Variable 'i' is not updated inside the loop. Currently you set i once and the while loop condition never become false. That is the reason why it shows out of memory. To avoid this mistake updat 'i' inside the loop. I guess you won't add the end operation of your methode (-1) so this could be a solution:
import java.util.*;
public class ListTakeInput {
/**
* #return
*/
public static List<Integer> takeInput() {
List<Integer> list = new ArrayList<>();
Scanner s = new Scanner(System.in);
int i = s.nextInt();
while (i != -1) {
list.add(i);
i = s.nextInt();
}
return list;
}
public static void print(List<Integer> list2) {
for (Integer integer : list2) {
System.out.print(integer + " ");
}
}
public static void main(String[] args) {
List<Integer> list2 = takeInput();
print(list2);
}
}
I have a class called ThreeSorts.java
The aim is to generate a random arraylist of size n - this works.
Then display the array - this works.
Then I have to prove that these sorting algorithms work, however when I pass the random generated array into one of the sorts like SortA(a);
and then display the array it does not get sorted the output is the same:
Generated ArrayList : (153),(209),(167),(117),(243),(67),(0),(148),(39),(188),
SortA ArrayList : (153),(209),(167),(117),(243),(67),(0),(148),(39),(188),
ThreeSorts.java:
import java.util.*;
public class ThreeSorts
{
private static ArrayList<Integer> CopyArray(ArrayList<Integer> a)
{
ArrayList<Integer> resa = new ArrayList<Integer>(a.size());
for(int i=0;i<a.size();++i) resa.add(a.get(i));
return(resa);
}
public static ArrayList<Integer> SortA(ArrayList<Integer> a)
{
ArrayList<Integer> array = CopyArray(a);
int n = a.size(),i;
boolean noswaps = false;
while (noswaps == false)
{
noswaps = true;
for(i=0;i<n-1;++i)
{
if (array.get(i) < array.get(i+1))
{
Integer temp = array.get(i);
array.set(i,array.get(i+1));
array.set(i+1,temp);
noswaps = false;
}
}
}
return(array);
}
public static ArrayList<Integer> SortB(ArrayList<Integer> a)
{
ArrayList<Integer> array = CopyArray(a);
Integer[] zero = new Integer[a.size()];
Integer[] one = new Integer[a.size()];
int i,b;
Integer x,p;
//Change from 8 to 32 for whole integers - will run 4 times slower
for(b=0;b<8;++b)
{
int zc = 0;
int oc = 0;
for(i=0;i<array.size();++i)
{
x = array.get(i);
p = 1 << b;
if ((x & p) == 0)
{
zero[zc++] = array.get(i);
}
else
{
one[oc++] = array.get(i);
}
}
for(i=0;i<oc;++i) array.set(i,one[i]);
for(i=0;i<zc;++i) array.set(i+oc,zero[i]);
}
return(array);
}
public static ArrayList<Integer> SortC(ArrayList<Integer> a)
{
ArrayList<Integer> array = CopyArray(a);
SortC(array,0,array.size()-1);
return(array);
}
public static void SortC(ArrayList<Integer> array,int first,int last)
{
if (first < last)
{
int pivot = PivotList(array,first,last);
SortC(array,first,pivot-1);
SortC(array,pivot+1,last);
}
}
private static void Swap(ArrayList<Integer> array,int a,int b)
{
Integer temp = array.get(a);
array.set(a,array.get(b));
array.set(b,temp);
}
private static int PivotList(ArrayList<Integer> array,int first,int last)
{
Integer PivotValue = array.get(first);
int PivotPoint = first;
for(int index=first+1;index<=last;++index)
{
if (array.get(index) > PivotValue)
{
PivotPoint = PivotPoint+1;
Swap(array,PivotPoint,index);
}
}
Swap(array,first,PivotPoint);
return(PivotPoint);
}
/////////////My Code////////////////
public static ArrayList<Integer> randomArrayList(int n)
{
ArrayList<Integer> list = new ArrayList<>();
Random random = new Random();
for (int i = 0; i < n; i++)
{
list.add(random.nextInt(255));
}
return list;
}
private static void showArray(ArrayList<Integer> a) {
for (Iterator<Integer> iter = a.iterator(); iter.hasNext();)
{
Integer x = (Integer)iter.next();
System.out.print(("("+x + ")"));
System.out.print(",");
//System.out.print(GetAge());
//System.out.print(") ");
}
System.out.println();
}
static void test(int n) {
//int n = 13;
ArrayList<Integer> a = randomArrayList(n);
System.out.println("Generated ArrayList : ");
showArray(a);
System.out.println("SortA ArrayList : ");
SortA(a);
showArray(a);
}
}
Test is called in main like this ThreeSorts.test(10);
Why is it not getting sorted even tho the random array is passed and there are no errors?
In your sample code you are only testing SortA which reads:
ArrayList<Integer> array = CopyArray(a);
...
return(array);
so actually it is taking a copy of your array, sorting it, and then returning you the sorted array.
So when you test it, instead of using:
SortA(a);
you need to use
a = SortA(a);
The type of data your function SortA returns is ArrayList<Integer>, which means it returns an array list of integers. You need to change the line SortA(a); to a = SortA(a);: this way a variable will receive the results of this function's work.
You have to set the returned value, otherwise a will not be sorted in test method. Change the way you call SortA(a) to:
static void test(int n) {
//int n = 13;
ArrayList<Integer> a = randomArrayList(n);
System.out.println("Generated ArrayList : ");
showArray(a);
System.out.println("SortA ArrayList : ");
a = SortA(a);
showArray(a);
}
instead of the method SortA(a); just use Collections.sort(a); inside static block. Like
ArrayList<Integer> a = randomArrayList(n);
System.out.println("Generated ArrayList : ");
showArray(a);
System.out.println("SortA ArrayList : ");
Collections.sort(a);
showArray(a);
Thats it.
I am trying to make a program that creates an ArrayList given the type as well as the values that will be put into the ArrayList. The input structure that we have to work with is "I 6 7 5 3 1 -1 2" with the I being the type Integer (or S for String, etc) and the first number (6) being how many values are in the ArrayList. I'm not sure how to instantiate the ArrayList.
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
String type = scan.next();
int length = scan.nextInt();
int counter = 0;
if (type.equals("I")) {
ArrayList<Integer> A = new ArrayList<Integer>;
}
else if (type.equals("S")) {
ArrayList<String> A = new ArrayList<String>;
}
else if (type.equals("D")) {
ArrayList<Double> A = new ArrayList<Double>;
}
else {
System.out.println("Invalid type");
}
while (scan.hasNext() && counter<length) {
String s1 = scan.next();
A.add(s1);
counter += 1;
}
System.out.print(A);
}
//Removes any duplicate values in the arraylist by checking each value after it
public static <E> ArrayList<E> removeDuplicates(ArrayList<E> list) {
ArrayList<E> inArray = list;
for (int i = 0; i<inArray.size(); i++) {
for (int j = i+1; j<inArray.size(); j++) {
if (inArray.get(i) == inArray.get(j)) {
inArray.remove(j);
}
}
}
return inArray;
}
//Shuffles the contents of the array
public static <E> void shuffle(ArrayList<E> list) {
E temp;
int index;
Random random = new Random();
for (int i = list.size()-1; i > 0; i--) {
index = random.nextInt(i + 1);
temp = list.get(index);
list.set(index, list.get(i));
list.set(i, temp);
}
System.out.print(list);
return;
}
//Returns the largest element in the given arraylist
public static <E extends Comparable<E>> E max(ArrayList<E> list) {
E max = Collections.max(list);
System.out.println(max);
return max;
}
I cannot in good conscious give you the answer you want, but rather I'll give you the answer you need.
DON'T DO THAT!
It serves no purpose at all. Datatype erasure at compile time of generics makes the ArrayList<Whatever> act equivalently to ArrayList<?> You cannot ascertain the generic type during runtime unless you type check the elements within the ArrayList
You might as well write this code, it'll give you the same exact results:
public static ArrayList<?> returnProper(String type) {
if(type.length() == 1 && "ISD".contains(type)) {
return new ArrayList();
} else {
System.out.println("Invalid type");
return null;
}
}
THUS, PLEASE DON'T DO THAT
Replace the second E with an "?" and then fix the method to return.
public static <T> ArrayList<?> returnProper(String type) {
if (type.equals("I")) {
return new ArrayList<Integer>();
} else if (type.equals("S")) {
return new ArrayList<String>();
} else if (type.equals("D")) {
return new ArrayList<Double>();
} else {
System.out.println("Invalid type");
}
return null;
}
I have 2 Strings:
A1=[Rettangolo, Quadrilatero, Rombo, Quadrato]
A2=[Rettangolo, Rettangolo, Rombo, Quadrato]
I want to obtain this: "I have found "Quadrilatero", instead of "Rettangolo" ".
If I use removeAll() or retainAll() it doesn't work because I have 2 instances of "Rettangolo".
In fact, if I use a1.containsAll(a2), I get true and I want false.
Thanks all for considering my request.
Use the remove method from ArrayList. It only removes the first occurance.
public static void main(String []args){
//Create ArrayLists
String[] A1 = {"Rettangolo", "Quadrilatero", "Rombo", "Quadrato"};
ArrayList<String> a1=new ArrayList(Arrays.asList(A1));
String[] A2 ={"Rettangolo", "Rettangolo", "Rombo", "Quadrato"};
ArrayList<String> a2=new ArrayList(Arrays.asList(A2));
// Check ArrayLists
System.out.println("a1 = " + a1);
System.out.println("a2 = " + a2);
// Find difference
for( String s : a1)
a2.remove(s);
// Check difference
System.out.println("a1 = " + a1);
System.out.println("a2 = " + a2);
}
Result
a1 = [Rettangolo, Quadrilatero, Rombo, Quadrato]
a2 = [Rettangolo, Rettangolo, Rombo, Quadrato]
a1 = [Rettangolo, Quadrilatero, Rombo, Quadrato]
a2 = [Rettangolo]
These two classes might help. Let me know how I can improve this further.
Feel free to use the code below in your own work.
I must point out that the current code does not take care of repeated list elements.
import java.util.List;
public class ListDiff<T> {
private List<T> removed;
private List<T> added;
public ListDiff(List<T> removed, List<T> added) {
super();
this.removed = removed;
this.added = added;
}
public ListDiff() {
super();
}
public List<T> getRemoved() {
return removed;
}
public List<T> getAdded() {
return added;
}
}
Util class.
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
public class ListUtil {
public static <T> ListDiff<T> diff(List<T> one, List<T> two) {
List<T> removed = new ArrayList<T>();
List<T> added = new ArrayList<T>();
for (int i = 0; i < one.size(); i++) {
T elementOne = one.get(i);
if (!two.contains(elementOne)) {
//element in one is removed from two
removed.add(elementOne);
}
}
for (int i = 0; i < two.size(); i++) {
T elementTwo = two.get(i);
if (!one.contains(elementTwo)) {
//element in two is added.
added.add(elementTwo);
}
}
return new ListDiff<T>(removed, added);
}
public static <T> ListDiff<T> diff(List<T> one, List<T> two, Comparator<T> comparator) {
List<T> removed = new ArrayList<T>();
List<T> added = new ArrayList<T>();
for (int i = 0; i < one.size(); i++) {
T elementOne = one.get(i);
boolean found = false;
//loop checks if element in one is found in two.
for (int j = 0; j < two.size(); j++) {
T elementTwo = two.get(j);
if (comparator.compare(elementOne, elementTwo) == 0) {
found = true;
break;
}
}
if (found == false) {
//element is not found in list two. it is removed.
removed.add(elementOne);
}
}
for (int i = 0; i < two.size(); i++) {
T elementTwo = two.get(i);
boolean found = false;
//loop checks if element in two is found in one.
for (int j = 0; j < one.size(); j++) {
T elementOne = one.get(j);
if (comparator.compare(elementTwo, elementOne) == 0) {
found = true;
break;
}
}
if (found == false) {
//it means element has been added to list two.
added.add(elementTwo);
}
}
return new ListDiff<T>(removed, added);
}
public static void main(String args[]) {
String[] arr1 = { "london", "newyork", "delhi", "singapore", "tokyo", "amsterdam" };
String[] arr2 = { "london", "newyork", "delhi", "singapore", "seoul", "bangalore", "oslo" };
ListDiff<String> ld = ListUtil.diff(Arrays.asList(arr1), Arrays.asList(arr2));
System.out.println(ld.getRemoved());
System.out.println(ld.getAdded());
ld = ListUtil.diff(Arrays.asList(arr1), Arrays.asList(arr2), new Comparator<String>() {
public int compare(String o1, String o2) {
return o1.compareTo(o2);
}
}); //sample for using custom comparator
System.out.println(ld.getRemoved());
System.out.println(ld.getAdded());
}
}
Here are three solutions.
An implementation that uses a remove method.
public static boolean same(List<String> list1, List<String> list2){
if (list1.size() != list2.size())
return false;
List<String> temp = new ArrayList<String>(list1);
temp.removeAll(list2);
return temp.size() == 0;
}
A solution that sorts then compares.
public static boolean same(List<String> list1, List<String> list2){
if (list1.size() != list2.size())
return false;
Collections.sort(list1);
Collections.sort(list2);
for (int i=0;i<list1.size();i++){
if (!list1.get(i).equals(list2.get(i)))
return false;
}
return true;
}
And, just for fun, you could do this by doing a word count difference between the two arrays. It wouldn't be the most efficient, but it works and possibly could be useful.
public static boolean same(List<String> list1, List<String> list2){
Map<String,Integer> counts = new HashMap<String,Integer>();
for (String str : list1){
Integer i = counts.get(str);
if (i==null)
counts.put(str, 1);
else
counts.put(str, i+1);
}
for (String str : list2){
Integer i = counts.get(str);
if (i==null)
return false; /// found an element that's not in the other
else
counts.put(str, i-1);
}
for (Entry<String,Integer> entry : counts.entrySet()){
if (entry.getValue() != 0)
return false;
}
return true;
}
This will find the intersection between two arrays for this specific case you have explained.
String[] A1 = { "Rettangolo", "Quadrilatero", "Rombo", "Quadrato" };
String[] A2 = { "Rettangolo", "Rettangolo", "Rombo", "Quadrato" };
ArrayList<String> a1 = new ArrayList<String>(Arrays.asList(A1));
ArrayList<String> a2 = new ArrayList<String>(Arrays.asList(A2));
a1.removeAll(a2);
System.out.println("I have found " + a1);
I hope this will help you
String[] A1 = {"Rettangolo", "Quadrilatero", "Rombo", "Quadrato"};
String[] A2 ={"Rettangolo", "Rettangolo", "Rombo", "Quadrato"};
Set<String> set1 = new HashSet<String>();
Set<String> set2 = new HashSet<String>();
set1.addAll(Arrays.asList(A1));
set2.addAll(Arrays.asList(A2));
set1.removeAll(set2);
System.out.println(set1);// ==> [Quadrilatero]
This is a pice of my code :
ArrayList<String> Alist= new ArrayList<String>();
ArrayList<String> Blist= new ArrayList<String>();
Alist.add("gsm");
Alist.add("tablet");
Alist.add("pc");
Alist.add("mouse");
Blist.add("gsm");
Blist.add("something");
Blist.add("pc");
Blist.add("something");
so i have two array list i want to compare all items and check if they are not equal and if they are to print out only the items that are not equal.
so i make something like this:
http://postimage.org/image/adxix2i13/
sorry for the image but i have somekind of bug when i post here a for looop.
and the result is :
not equals..:tablet
not equals..:pc
not equals..:mouse
not equals..:gsm
not equals..:tablet
not equals..:pc
not equals..:mouse
not equals..:gsm
not equals..:tablet
not equals..:pc
not equals..:mouse
not equals..:gsm
not equals..:tablet
i want to print only the 2 that are not equal in the example they are gsm and pc
not equals..:gsm
not equals..:pc
Don't use != to compare strings. Use the equals method :
if (! Blist.get(i).equals(Alist.get(j))
But this wouldn't probably fix your algorithmic problem (which isn't clear at all).
If what you want is know what items are the same at the same position, you could use a simple loop :
int sizeOfTheShortestList = Math.min(Alist.size(), Blist.size());
for (int i=0; i<sizeOfTheShortestList; i++) {
if (Blist.get(i).equals(Alist.get(i))) {
System.out.println("Equals..: " + Blist.get(i));
}
}
If you want to get items that are in both lists, use
for (int i = 0; i < Alist.size(); i++) {
if (Blist.contains(Alist.get(i))) {
System.out.println("Equals..: " + Alist.get(i));
}
}
You can use the RemoveAll(Collection c) on one of the lists, if you happen to know if one list always contains them all.
You could use the following code:
ArrayList<String> Alist = new ArrayList<String>();
ArrayList<String> Blist = new ArrayList<String>();
Alist.add("gsm");
Alist.add("tablet");
Alist.add("pc");
Alist.add("mouse");
Blist.add("gsm");
Blist.add("something");
Blist.add("pc");
Blist.add("something");
for (String a : Alist)
{
for (String b : Blist)
{
if (a.equals(b))
{
System.out.println("Equals " + a);
break;
}
}
}
Output is:
Equals gsm
Equals pc
right now your comparing each element to all of the other ones. Do something like
for (int i = 0; i < Alist.size(); i++) {
if (!Alist.get(i).equals(Blist.get(i)) {
// print what you want
}
}
Thats of course assuming both lists have the same length.
Rather than writing code to manually compare list elements you might consider using Apache Commons Collections.
import org.apache.commons.collections.CollectionUtils;
List listA = ...;
List listB = ...;
Collection intersection = CollectionUtils.intersection(listA, listB);
import java.util.HashSet;
public class CheckSet<T> extends HashSet<T>{
#Override
public boolean add(T e) {
if (contains(e)) {
remove(e);
return true;
} else {
return super.add(e);
}
}
}
Add all elements of both of your lists to a CheckSet intance, and at the end it will only contain the ones not equal.
Here is one way:
public static boolean compare(List<String> first, List<String> second) {
if (first==null && second==null) return true;
if (first!=null && second==null) return false;
if (first==null && second!=null) return false;
if ( first.size()!=second.size() ) return false;
HashMap<String, String> map = new HashMap<String, String>();
for (String str : first) {
map.put(str, str);
}
for (String str : second) {
if ( ! map.containsKey(str) ) {
return false;
}
}
return true;
}
public static void main(String args[] ) throws Exception {
List<String> arrayList1 = new ArrayList<String>();
arrayList1.add("a");
arrayList1.add("b");
arrayList1.add("c");
arrayList1.add("d");
List<String> arrayList2 = new ArrayList<String>();
arrayList2.add("a");
arrayList2.add("b");
arrayList2.add("c");
arrayList2.add("d");
boolean isEqual = false;
if(arrayList1.size() == arrayList2.size()){
List<String> arrayListTemp = new ArrayList<String>();
arrayListTemp.addAll(arrayList1);
arrayListTemp.addAll(arrayList2);
HashSet<Object> hashSet = new HashSet<Object>();
hashSet.addAll(arrayListTemp);
if(hashSet.size() == arrayList1.size() &&
hashSet.size() == arrayList2.size()){
isEqual = true;
}
}
System.out.println(isEqual);
}
we can compare two different size arrayList in java or Android as follow.
ArrayList<String> array1 = new ArrayList<String>();
ArrayList<String> array2 = new ArrayList<String>();
array1.add("1");
array1.add("2");
array1.add("3");
array1.add("4");
array1.add("5");
array1.add("6");
array1.add("7");
array1.add("8");
array2.add("1");
array2.add("2");
array2.add("3");
array2.add("4");
for (int i = 0; i < array1.size(); i++) {
for (int j=0;j<array2.size();j++) {
if (array1.get(i) == array2.get(j)) {
//if match do the needful
} else {
// if not match
}
}
}
import java.util.Arrays;
public class ExampleContains {
public static boolean EligibleState(String state){
String[] cities = new String[]{"Washington", "London", "Paris", "NewYork"};
boolean test = Arrays.asList(cities).contains(state)?true:false;
return test;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println(EligibleState("London"));
}
}