I Use Generics, But Not This Class<T> thing! - java

I am trying to call this method to concat two arrays using Google Collections
public static <T> T[] concat(T[] first,
T[] second,
Class<T> type)
It's returning empty results. I am using
ObjectArrays.concat(array1, array2, Blah.class)
which is the only thing that compiles.
array1 and array2 are of type Blah[].
What's the right syntax?
Bonus question: do other collections libraries have documentation with examples?
Edit: Problem was my bone-headed code.
public void register(ButtonPair[] pairs) {
pairs = ObjectArrays.concat(this.pairs, pairs, ButtonPair.class);
}
the right side of the thing is okay, but the left side is not assigning to this.pairs due to the ambiguity. Sorry! And hats off to Google Collections!

The following worked for me:
String[] arr1 = { "abc", "def" };
String[] arr2 = { "ghi", "jkl" };
String[] result = ObjectArrays.concat(arr1, arr2, String.class);
How are you getting the result from concat()?

For some example usage of the Google Collections classes, check out the unit tests.
For example:
String[] result = ObjectArrays.concat(
new String[] { "a", "b" }, new String[] { "c", "d" }, String.class);
assertEquals(String[].class, result.getClass());
assertContentsInOrder(Arrays.asList(result), "a", "b", "c", "d");
So, what the Class<T> notation means is that it needs you to specify what class the objects in the other two argument arrays belong to.

Your syntax looks totally correct. I think the problem must be elsewhere. Are you 100% certain about the input values? Here is a test case:
import com.google.common.collect.ObjectArrays;
public class ObjectArrayTest
{
public static void main(String[] args)
{
String[] first = new String[] { "Fire", "Earth" };
String[] second = new String[] { "Water", "Air" };
String[] result = ObjectArrays.concat(first, second, String.class);
for (String s : result)
{
System.out.println (s);
}
}
}

Isn't this because you are not assigning the result to the instance variable but to the method variable.
That is this:
public void register(ButtonPair[] pairs) {
pairs = ObjectArrays.concat(this.pairs, pairs, ButtonPair.class);
}
should be
public void register(ButtonPair[] pairs) {
this.pairs = ObjectArrays.concat(this.pairs, pairs, ButtonPair.class);
}
Incidentally, this is why at our shop we have have a different naming convention for method parameters and variables than that for instance variables (though not the awful prefixing/suffixing of instance variables like _someInstanceVar).

Related

(Java) How to store selected elements from a list into array

I have a list of elements:
private List<Track> selection;
And I want to implement a function public Track[] selection()
which returns an array of selected tracks. How to implement this?
I was going to implement this: Swings: storing the selected values from List into an array. method, however it applies only for known number of elements.
EDIT: Sorry to ask such a newbie question, but I tried any possible ways previously and nothing worked. OOP is new for me, and where else to find answers for questions if not here? ^_^
Consider the following minimal example for copying a list of Strings into an array and printing it:
import java.util.Arrays;
import java.util.List;
public class Main {
public static void main (String[] args) {
List<String> stringList = Arrays.asList("H", "e", "l", "l", "o");
String[] stringArray = stringList.toArray(new String[0]);
System.out.println(Arrays.toString(stringArray)); // [H, e, l, l, o]
}
}
Assuming the selection is a global value
public Track[] selection()
{
return selection.toArray(new Track[0]);
}
Else, you can pass the selection List as an argument to the method;
public Track[] selection(List<Track> input)
{
return input.toArray(new Track[0]);
}
and then
Track[] result = selection( selectionList ) // List selection
public Track[] selection() {
return this.selection.stream().filter(predicate-here).toArray(Track[]::new);
}
Your predicate might be, for instance: elem -> elem.getName().equals("something")

How to pass dynamic string values to a method?

I am trying to create a method that should dynamically accept the string values and store it in an array list.Am trying to achieve method overloading here. Please see the below example and help me resolve in this:
public static void main(String[] args){
verifyFilesInFolder("folder1", "file1", "file2", "file3");
verifyFilesInFolder("folder2", "file1", "file2");
}
verifyFilesInFolder(String folder, ArrayList ???)
{
List<String> list = new ArrayList<String>();
int size=list.size();
for(int i=0; i<size;i++){
list.add(i); // is this correct??
}
}
After storing it in the array list, i want to compare this expected list with Actual list captured from the application by sorting.
Hope you got the point am looking for. If not ArrayList, please suggest me a way to achieve this by having only one method but the number of files may change while calling that method.
You have 2 options:
Overloading
Define mulitple methods with the same names but different numbers of arguments:
public void func(String s1) { ... }
public void func(String s1, String s2) { ... }
public void func(String s1, String s2, String s3) { ... }
Varargs
Define a single method that takes any number of args:
public void func(String ...strings) {
// strings is of type String[]
String s1 = strings[0];
String s2 = strings[1]; // note, be careful with ArrayIndexOutOfBoundsException
// generally use a for-each loop
}
This can be called as:
func("1");
func("1", "2");
func("1", "2", "3");
func(new String[] {"1", "2", "3"});
EDIT:
If you want to add these values to a List, you can do this:
verifyFilesInFolder(String folder, String ...strings) {
List<String> list = Arrays.asList(strings);
for (String s : list) System.out.println(s);
}
Some inputs/outputs:
verifyFilesInFolder("folder", "item1"); -> prints "item1"
verifyFilesInFolder("folder", "item1", "item2"); -> prints "item1" and "item2"
verifyFilesInFolder("folder"); -> prints nothing
verifyFilesInFolder(); -> won't compile

Initializing an object in a method and creating a copy of it in another method

I'm trying to initialize a string array with 3 empty strings in a static void method. Then I make a copy of that string array in another static String[] method.
I have tried several ways to do this, but what is the best way to do this?
public static void createEmptyStrings() {
String[] str = new String[]{"", "", ""};
}
public static String[] copyStrings() {
// return an empty string
}
You could do something like this:
public static String[] getStrings(){
String[] strings = {"", "", ""};
return strings
}
public static String[] copyStrings(String[] stringArray){
return stringArray.clone();
}
// Sample Usage
String[] originalStrings = getStrings();
String[] copiedStrings = copyStrings(originalStrings);
The .clone() method is very helpful in java to create a copy of an object and not just reference it as many people accidentally do.
If you want the array to have 3 slots that are empty instead of being filled with "" than change line two to:
public String[] strings = new String[3];

Is it possible to declare global array of type String[][]?

What i wanted do is this:
class test{
public static String[][] p;
}
But something is wrong.
When i try to write sth to it by using:
p[][]={...};
It says: "p cannot be resolved to a type".
EDIT:
Ok, I see there were some problems with understanding what i am talking about so i post a code here.
public class Test{
static String[][] plansza;
public static void main(String []arg){
p[][]={ {" ","A", "B", "C", "D", "E", "F", "G", "H"},
{"1.","0","1","0","1","0","1","0","1"},
{"2.","1","0","1","0","1","0","1","0"},
{"3.","0","1","0","1","0","1","0","1"},
{"4.","0","0","0","0","0","0","0","0"},
{"5.","0","0","0","0","0","0","0","0"},
{"6.","2","0","2","0","2","0","2","0"},
{"7.","0","2","0","2","0","2","0","2"},
{"8.","2","0","2","0","2","0","2","0"}
};
}
To create array normally you need to at least set first dimension of array, but normally you do it like
1) new Type[dim1][dim2]..[dimN]
You can skip dimensions if you initialize arrays with elements like
2) new Type[][]..[]{{..{elements},},..}}
But if you are initializing your array with elements in the same place where you are declaring it then you can skip new Type[][]...[] part and just use {{..{elements},},..}} like
3) Type[][]..[] myArray = {{..{elements},},..}}
In your case you are having case 2) because you are not initializing your array in place you declared it. So instead of
p[][] = {
{" ","A","B","C","D","E","F","G","H"},
...
};
you need to write it as
p = new String[][]{
{" ","A","B","C","D","E","F","G","H"},
...
};
Try like the follwoing
public class Test{
static String[][] plansza;
public static void main(String []arg){
plansza = new String[][] { {" ","A", "B", "C", "D", "E", "F", "G", "H"},
{"1.","0","1","0","1","0","1","0","1"},
{"2.","1","0","1","0","1","0","1","0"},
{"3.","0","1","0","1","0","1","0","1"},
{"4.","0","0","0","0","0","0","0","0"},
{"5.","0","0","0","0","0","0","0","0"},
{"6.","2","0","2","0","2","0","2","0"},
{"7.","0","2","0","2","0","2","0","2"},
{"8.","2","0","2","0","2","0","2","0"}
};
}
}
you must place new String[][]{....}; before assign it to plansza
Try this type of initialization:
public static String[][] s = new String[][]{
{"A", "B", "C"},
{"D", "E", "F"}
};
This would define dinamically your multidimensional Array
You can only use array constants in initializers.
Therefore:
// will compile
public static String[][] p = {{"foo", "bar"}};
// will compile
public static String[][] p;
static {
p = new String[][]{{"foo", "bar"}};
}
// won't compile
public static String[][] p;
static {
p = {{"foo", "bar"}};
}
Understand that p is a variable of type String[][] , thus initialize it in the following way
p = new String[][]{...};
In the above code p which is of type String[][] is assigned to an object initialized of the same type.
when you try to assign values, you can specify the indices like this
p[i][j] = "value";

Strange string array declaration Syntax

private final String[] okFileExtensions = new String[] { "csv" };
Would someone please explain why {} is written after a String array declaration?
Thanks.
It's an array of one element. In this case containing the String "csv".
When written as part of a declaration, this can be written in a more concise form:
private final String[] okFileExtensions = { "csv" };
Multiple-element arrays use commas between values. There needn't be any values at all.
private final String[] okFileExtensions = { "csv", "tsv" };
private final String[] noFileExtensions = { };
It may be worth noting that although the reference is final the array is not. So you can write:
okFileExtensions[0] = "exe";
A way to get around this is to switch to collections and use an unmodifiable implementation:
private final Set<String> okFileExtensions = Collections.unmodifiableSet(
new HashSet<String>(Arrays.asList({
"csv"
}));
JDK8 is intended to have enhancement to collections that will make this more concise. Probably List and Set literals within the language. Possibly:
private final Set<String> okFileExtensions = { "csv" };
Collections should generally be preferred over arrays (for reference types).
That's the Java's valid syntax for array declaration.
You may use that when you are passing an array without declaring a variable:
public void printArray( String [] someArray ) {
for( String s : someArray) {
System.out.println( s );
}
}
And invoke it like this:
printArray( new String [] { "These", "are", "the", "contents"} );
The curly braces can only be used when declaring the array so the following is not allowed:
Stirng [] a;
a = {"on", "two"};
Creating an array of strings inline.
I think a less verbose (also confusing) declaration would have been :
private final String[] okFileExtensions = {"csv"};

Categories