I have created a default constructor which creates an empty "hand".
public Hand() {
hand = new ArrayList();
}
Whats the most efficient way to have a second constructor take an Array of cards, then add them a hand?
I would have one constructor to do both.
public Hand(Card... cards) {
hand = Arrays.asList(cards);
}
Or an ArrayList copy as Rohit Jain suggests.
You can do it like this: -
public Hand(String[] hands) {
hand = new ArrayList<String>(Arrays.asList(hands));
}
Or, you can iterate over your string array, and add individual elements to your ArrayList.
public Hand(String[] hands) {
hand = new ArrayList<String>();
for (String elem: hands)
hand.add(elem);
}
P.S: - Always declare a Generic Type List.
There's another option, Collections.addAll:
public Hand(Card[] cards) {
hand = new ArrayList<Card>();
Collections.addAll(hand, cards);
}
According to the documentation:
Adds all of the specified elements to the specified collection.
Elements to be added may be specified individually or as an array. The
behavior of this convenience method is identical to that of
c.addAll(Arrays.asList(elements)), but this method is likely to run
significantly faster under most implementations.
Related
I have a Engineer class. And I'm creating a empty arraylist which is engineer type.
I'm creating a method to check arraylist, if arraylist isn't null it has to give me index 0. But if arraylist is null. My method has to create a new Engineer object and add to empty arraylist. After that adding, I'm expecting my method to give me index 0. But it throws IndexOutOfBoundsException. I know I missed some simple things, but I couldn't figure out how to fix.
ArrayList<Engineer> newEmptyEngineerList = new ArrayList<>();
findLastEngineer(newEmptyEngineerList);
public static void findLastEngineer(ArrayList aa){
if (aa.get(0)!=null){
System.out.println(aa.get(0));
}
else {
Engineer eng = new Engineer();
aa.add(0,eng);
System.out.println(aa.get(0));
}
}
You have to make sure that the list is not empty before calling get(0) on it.
Also avoid using raw array list and prefer interface List to its implementation when using as function parameters or return type.
public static void findLastEngineer(List<Engineer> aa) {
if (aa.isEmpty()){
aa.add(new Engineer());
}
// get and print last element
System.out.println(aa.get(aa.size() - 1));
}
This seems very simple but I can't quite figure out why this isn't working.
I want to reverse the elements in my LinkedList which I have a working method for, but I can't return the value as my prof wants it to be a void method. How would I go about this?
import java.util.LinkedList;
public class ListUtil {
public static void reverse(LinkedList<String> strings) {
LinkedList<String> reverseLinkedList = new LinkedList<>();
for(int i = strings.size() - 1; i >= 0; i--) {
reverseLinkedList.add(strings.get(i));
}
strings = reverseLinkedList;
System.out.println(strings);
}
}
import java.util.LinkedList;
public class ReverseTester {
public static void main(String[] args) {
LinkedList<String> employeeNames = new LinkedList<>();
employeeNames.addLast("Dick");
employeeNames.addLast("Harry");
employeeNames.addLast("Romeo");
employeeNames.addLast("Tom");
ListUtil.reverse(employeeNames);
System.out.println(employeeNames);
System.out.println("Expected: [Tom, Romeo, Harry, Dick]");
}
}
In my ListUtil class, it does reverse the list, but doesnt return a value (as it is void) but I don't know how to go about setting employeeName in the ReverseTester class.
I know this is probably super simple but I have not been able to figure this out for the life of me, any help is greatly appreciated.
Empty and re-fill the existing list rather than replacing it.
public static void reverse(LinkedList<String> strings) {
List<String> temp = new ArrayList<>(strings); // Copy the contents of the original list. Pass the original list to constructor of our duplicate list.
strings.clear(); // Empty the original list.
for (String e : temp)
strings.addFirst(e); // Refill the original list using elements from our duplicate list.
}
Or simply
public static void reverse(LinkedList<String> strings) {
Collections.reverse(strings);
}
Non-primitive Java object are stored by reference so you don't need to return anything from ListUtil::reverse. Any changes made to the object in the function will be reflected in ReverseTester.java. This happens because, again, non-primitive Java objects are stored by reference. Basically your code does exactly what you want it to do. You make a LinkedList, populate it with items, and then reverse those items.
You will have a problem with System.out.println(employeeNames); though. Because that will just print the object's formal name and not it's contents. If you want to print the contents of a list in Java you can do:
for (String name : employeeNames) {
System.out.println(t);
}
This is my first answer so please ask any questions if I wasn't clear enough!
I've got a function to create syllables for words.
I use it like this: syllables(word1field); - creates List with syllables: aa,bb,cc
and syllables(word2field); - creates List with syllables: dd,ee,ff
And in the result I get dd,ee,ff, but I need aa,bb,cc,dd,ee,ff.
Is there possibility to append second list to first?
You get dd,ee,ff because when you call the same method again, it overrides the first ArrayList that is created.
The best thing you could do, that I can think of, is to make your ArrayList global because currently you just keep getting rid of the previous values and create a new ArrayList with the new values you give it. Try doing something like:
public class MyClass {
private List<String> myArray;
public MyClass() {
myArray = new ArrayList<String>();
}
public void syllables(wordfield) {
// do whatever you need to with wordfield
myArray.add(syllable);
}
I don't know how you've got everything laid out but this is the best solution I can think of.
i've digging around about the same issue but i couldn't find the same as i had
i want to create an array without declaring the size because i don't know how it will be !
to clear the issue i'd like to give you the code that i'm looking up for
public class t
{
private int x[];
private int counter=0;
public void add(int num)
{
this.x[this.counter] = num;
this.counter++;
}
}
as you see the user could use the add function to add element to the array 10000 times or only once so it's unknown size
Using Java.util.ArrayList or LinkedList is the usual way of doing this. With arrays that's not possible as I know.
Example:
List<Float> unindexedVectors = new ArrayList<Float>();
unindexedVectors.add(2.22f);
unindexedVectors.get(2);
You might be looking for a List? Either LinkedList or ArrayList are good classes to take a look at. You can then call toArray() to get the list as an array.
As others have said, use ArrayList. Here's how:
public class t
{
private List<Integer> x = new ArrayList<Integer>();
public void add(int num)
{
this.x.add(num);
}
}
As you can see, your add method just calls the ArrayList's add method. This is only useful if your variable is private (which it is).
Once the array size is fixed while running the program ,it's size can't be changed further.
So better go for ArrayList while dealing with dynamic arrays.
How about this
private Object element[] = new Object[] {};
I think what you really want is an ArrayList or Vector. Arrays in Java are not like those in Javascript.
I design new IntSet Class that use ArrayList. first, i extends Intset by ArrayList and i start implement method. i face some problem in my union() method. here is my code...
public class IntSet extends ArrayList<Integer>{
private static final long serialVersionUID = 1L;
private ArrayList<Integer> intset;
public IntSet(){
this.intset = new ArrayList<Integer>();
}
public IntSet(ArrayList<Integer> intset){
this.intset = intset;
}
public void insert(int x){
this.intset.add(x);
}
#Override
public Integer remove(int x){
int index = intset.indexOf(x);
this.intset.remove(index);
return 1;
}
#Override
public int size(){
return this.intset.size();
}
#Override
public Integer get(int index){
return this.intset.get(index);
}
public boolean member(int x){
if(intset.indexOf(x)==-1) return false;
else return true;
}
public IntSet union(IntSet a){
IntSet intersectSet = new IntSet();
intersectSet.insert(0);
intersectSet.insert(1);
System.out.println(intersectSet.size());
System.out.println(intersectSet.contains(1));
for(int i=0; i<a.size(); i++){
}
return intersectSet;
}
public String toString(){
if(intset.size()==0) return "[]";
String s = "[" + intset.get(0).toString();
for(int i=1; i<intset.size(); i++){
s += "," + intset.get(i).toString();
}
return s += "]";
}
}
In method
union(IntSet a);
I constract new Intset object then add 2 value (0, 1) into intersectSet variable.
intersectSet.insert(0);
intersectSet.insert(1);
then i print size of intersectSet it shown me 2 that is correct!
but when i need to check that there is 1 in intersectSet or not? it shown me false.
System.out.println(intersectSet.contains(1));
In fact it should show me true because in intersectSet have integer 1.
anything wrong about my code and should i extends ArrayList for IntSet class?
Some suggestions on the class design:
Don't have your class extend ArrayList. A "set" really shouldn't be extending List. However, you should probably implement Set. This will have the added bonus of the compiler telling you what methods you need to implement for a set.....
For fastest performance (but more work!), you may want to use an internal array rather than an ArrayList.
Consider making the structure immutable, with functions that return a new copy rather than mutating the set in place. Depending on your usage, this may be a better solution, especially if you are mostly dealing with small, non-changing sets.
Again depending on your usage, you may want to override hashCode and equals to implement value based equality
When you construct the Intset with an ArrayList, you should ideally defensively copy (clone) the ArrayList. You don't want you set to change if someone mutates the original ArrayList.
The problem here is that you actually have 2 ArrayLists. The IntSet class IS A ArrayList, but this class contains a second ArrayList intset. Get rid of one of these ArrayLists. To demonstrate this add this second line:
System.out.println(intersectSet.contains(1));
System.out.println(intersectSet.intset.contains(1));
this will output:
false
true
So you are going to have to make a choice, do I inherit from ArrayList or do I contain an ArrayList. Of course what I am getting at here is Item 16 from Effective Java, Favor composition over inheritance.
You are both extending ArrayList and managing your own internal ArrayList object, this means that for all the methods which you have overridden you are interacting with your intset member variable, otherwise you are interacting with the inherited internal representation used by the ArrayList superclass. If you override the contains method you will get the correct behaviour.
I suggest that you drop the subclassing of ArrayList and instead implement the List or Set interfaces, although this depends on the exact problem you've been asked to solve.
you need to override contains method.
public boolean contains(Object o) {
return intset.contains(o);
}
and the rest of ArrayList methods that related to its elements.
and i doesn't seems to me a good solution. you may try better approach.