I have one method that returns an object with two arraylists:
return new Object[] {work, play};
I am trying to get them back out in another method. I have tried casting to ArrayList but I get the error 'array required, but java.lang.Object found'.
ArrayList setWork = (ArrayList)obj[0];
ArrayList setPlay = (ArrayList)obj[1];
Full code for ArrayList creation:
public static Object[] getWorkandPlay(ArrayList al) {
ArrayList work = new ArrayList();
ArrayList play = new ArrayList();
for (int i=0; i<al.size(); i++){
String item = (String) al.get(i);
if (item.startsWith("w.")) {
System.out.println("w " + item);
work.add(item);
} else if (item.startsWith("p.")) {
System.out.println("p " + item);
play.add(item);
} else {
System.out.println("Entries must start with either w. or p.\n");
}
}
return new Object[] {work, play};
}
I am doing something like this based on your code and it works...
class Test{
public static Object[] getWorkandPlay(ArrayList al) {
ArrayList work = new ArrayList();
ArrayList play = new ArrayList();
for (int i=0; i<al.size(); i++){
String item = (String) al.get(i);
if (item.startsWith("w.")) {
System.out.println("w " + item);
work.add(item);
} else if (item.startsWith("p.")) {
System.out.println("p " + item);
play.add(item);
} else {
System.out.println("Entries must start with either w. or p.\n");
}
}
return new Object[] {work, play};
}
public static void main(String[] args) {
ArrayList<String> al=new ArrayList<>();
al.add("w. test");
al.add("p. test");
Object[] obj=getWorkandPlay(al);
ArrayList setWork = (ArrayList)obj[0];
ArrayList setPlay = (ArrayList)obj[1];
}
}
output
w w. test
p p. test
return new Object[] {work, play}; i think returns an array of object. Try ArrayList result = new ArrayList();
put work andd play inside result then return result. Then
In your calling code, you should set the reference type of obj as an Object array.
You probably have
Object obj = getWorkandPlay(anArrayList); in your code. Change it to Object[] obj = getWorkandPlay(anArrayList);.
You probably have a typo somewhere in your code. This compiles for me:
import java.util.*;
public class SampleClass {
public static void main(String[] args) {
// Create an ArrayList and add some sample Strings
ArrayList al = new ArrayList();
al.add("w. test");
al.add("p. test");
Object[] obj = getWorkandPlay(al);
ArrayList setWork = (ArrayList)obj[0];
ArrayList setPlay = (ArrayList)obj[1];
}
public static Object[] getWorkandPlay(ArrayList al) {
ArrayList work = new ArrayList();
ArrayList play = new ArrayList();
for (int i=0; i<al.size(); i++){
String item = (String) al.get(i);
if (item.startsWith("w.")) {
System.out.println("w " + item);
work.add(item);
} else if (item.startsWith("p.")) {
System.out.println("p " + item);
play.add(item);
} else {
System.out.println("Entries must start with either w. or p.\n");
}
}
return new Object[] {work, play};
}
}
Related
I have to send a array list of arrays to the test case using the dataprovider annotation. I have the below code but it is giving illegal argument exception. My arraylist size is 4096. Do I need to give such many arguments in test method.
#Test(dataProvider="combination_list")
public void checkbox_combination(List<int[]> obj) {
/*for(int i=0;i<=4095;i++) {
}*/
}
#DataProvider(name="combination_list")
public static Object[][] get_Combination_list() {
List<int[]> combinations_with_int_array = new ArrayList<int[]>();
int size_combination;
for(int i=0;i<=4095;i++) {
String checkbox_combination =Combination_List.intToString(i,12);
int[] single_combination = new int[12];
for (int j=0;j<=11;j++) {
if(j<11)
{
single_combination[j]=Integer.parseInt(checkbox_combination.substring(j, j+1));
}
else
{
single_combination[j]=Integer.parseInt(checkbox_combination.substring(j));
}
}
combinations_with_int_array.add(single_combination);
}
size_combination=combinations_with_int_array.size();
System.out.println("No of combinations : "+size_combination);
Object objArray[][] = new Object[size_combination][];
for(int i=0;i<size_combination;i++){
objArray[i] = new Object[1];
objArray[i][0] = combinations_with_int_array.get(i);
}
return objArray;
}
combinations_with_int_array is an arrayList of int[].
objArray[i][0] = combinations_with_int_array.get(i);
When you do a get on the list, it give you int[] which is the type of the argument, which it is adding to the Object[][]. So your test method should have the same argument.
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'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;
}
I'm making a little card deck program that uses an ArrayList for the deck. One of the limitations set upon me is that the method in which I "deal" the cards must be an Arraylist type. The problem I'm running into is that I don't know how to return just a specific index value from the ArrayList. See below.
public ArrayList deal(int n, boolean up){
Card card0 = new Card();
boolean cardFace = card0.state(up);
return al.get(0); //<-- This doesn't work, Netbeans says that it is a string type
//not an ArrayList type. The only thing it will actually
//allow me to return is:
return.al; // But this doesn't work, I don't need to return the whole list,
// just the first element, but Netbeans calls that a String type, not
// ArrayList
So how can I return the first item of the List and still have it be the correct type? The rest of the code doesn't matter, just the Method type and return statement.
EDIT: As requested
package deckofcards;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;
public class Deck{
ArrayList<String> al = new ArrayList<>();
public void shuffle(){
Collections.shuffle(al);
}
public String displayDeck(){
String returnDeck = "";
for(int i = 0; i < al.size(); i++){
String printDeck = al.get(i);
returnDeck += printDeck;
}
return returnDeck;
}
public ArrayList deal(int n, boolean up){
Card card0 = new Card();
boolean cardFace = card0.state(up);
return al.get(0);
}
public void populate(){
al.add(0, "Ace of Spades");
al.add(1, "Two of Spades");
al.add(2, "Three of Spades");
//yadaa yadaa
If you cannot change the signature and it is mandatory to return an arraylist, then you can create an arraylist with just one element and return it. Something like this:
ArrayList returnList = new ArrayList();
returnList.add(al.get(0));
return returnList;
Does not look great to me :-(
In your specific case, al is an ArrayList<String>. That means al.get(...) returns a String. However, your method is declared as returning an ArrayList, which is not a String. You will either need to change your method return type to String, or you will need to construct a new ArrayList and add your single string to it and return that.
Your declared return type needs to match the object you are returning. So for example:
ArrayList<String> al = ...;
String getSingleItem (int index) {
return al.get(index);
}
ArrayList<String> getSingleItemAsArrayList (int index) {
ArrayList<String> single = new ArrayList<String>();
single.add(al.get(index));
return single;
}
ArrayList<String> getItems () {
return al;
}
By the way, it's generally better to specify the type parameter to ArrayList, e.g. ArrayList<Whatever>, as this can save you a lot of casting things around / unchecked conversions and will give you compile-time checking of types.
Is there a reason that you have to return an ArrayList? Essentially, you are trying to create a method that takes a deck, picks a card, and then returns a deck. You could try and use the subList method someone mentioned above. You could create a new ArrayList containing only the card you want, but that's not very efficient. Or, if your goal is to actually return the whole deck, but with the correct card on top (aka in the first position of the ArrayList), there's lots of info about rearranging values in an ArrayList online.
EDIT: Based on your full code, it looks like the goal is to flip the first card face up. You should do that (not gonna do your homework for you!) and then return the ArrayList that the method took in. IRL, imagine handing someone a deck, they flip the first card face up, then hand the deck back to you.
//ADDING AND deleting employees
//Displaying employee list
public class EployeeDB {
static ArrayList e = new ArrayList<>();
public static boolean addEmployee(Employee e1) {
e.add(e1);
System.out.println("Employee added");
return true;
}
public static boolean deleteEmployee(int ecode) {
int temp = 0;
for (int i = 0; i < e.size(); i++) {
if (e.get(i).getID() == ecode) {
temp = temp + 1;
e.remove(i);
break;
}
}
if (temp == 1)
System.out.println("Emp deleted");
else
System.out.println("Deletion unsuccessful, check ecode again");
return true;
}
public static String showPaySlip(int ecode) {
double salary = 0;
int temp = 0;
for (int i = 0; i < e.size(); i++) {
if (e.get(i).getID() == ecode) {
temp = temp + 1;
salary = e.get(i).getSalary();
break;
}
}
if (temp == 1)
return "Salary is" + salary;
else
return "No employye found with the specified ecode";
}
public static ArrayList<Employee> listAll() {
return e;
}
public static void main(String[] args) {
Employee e1 = new Employee();
e1.setID(20);
e1.setName("sai");
e1.setSalary(150.00);
addEmployee(e1);
Employee e2 = new Employee();
e2.setID(30);
e2.setName("kumar");
e2.setSalary(1500.00);
addEmployee(e2);
deleteEmployee(30);
System.out.println(showPaySlip(30));
for (int i = 0; i < e.size(); i++)
System.out.println(
listAll().get(i).getID() + " " + listAll().get(i).getName() + " " + listAll().get(i).getSalary());
}
}
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"));
}
}