I am calling a library method on a fluent API that takes a var args of Strings. when I call it I always pass at least three strings and then a few more depending on circumstance.
Can have a final static array or something to capture the three Strings that are always passed?
Perhaps something like this:
public class Overloaded {
private static final String[] CONST_ARR = {"1", "2", "3"};
public static void main(String[] args) {
Overloaded o = new Overloaded();
o.withConstantStrings();
String[] a = {"1", "2"};
o.withAdditionalStrings(a);
}
public void withConstantStrings() {
libraryVarArgsCode(CONST_ARR);
}
public void withAdditionalStrings(String... additional) {
String[] join = new String[additional.length + CONST_ARR.length];
System.arraycopy(CONST_ARR, 0, join, 0, CONST_ARR.length);
System.arraycopy(additional, 0, join, CONST_ARR.length, additional.length);
libraryVarArgsCode(join);
}
public void libraryVarArgsCode(String... args) {
// librabry code here
}
}
Here is an idea:
static final String[] RESERVED = {"A", "B", "C"};
...
libMethod(Stream.concat(Arrays.stream(RESERVED), Stream.of("D")).toArray(String[]::new));
Related
What I'm trying to achieve - have a list that is not shared by all the objects i.e. have a unique list for each objects created from a class, something similar to the below code which obviously results in an error because the ArrayList needs to be static.
public class Foo{
public ArrayList<String> chain = new ArrayList<>();
public addElement(String input){
this.chain.add(input);
}
}
public printList(){
for(String s : this.chain){
System.out.println(s);
}
}
public static void main(){
Foo x = new Foo();
Foo y = new Foo();
x.addElement("abc");
x.addElement("pqr");
y.addElement("lmn");
y.addElement("rty");
x.printList(); //print abc pqr
y.printList(); //print lmn rty
}
Is there a way to achieve the above outputs?
Your brackets are all over the place, you miss function return types and their names and calls don't match, moreso your main doesn't follow the normal pattern. In other words it could use some help.
public class Foo
{
public ArrayList<String> chain = new ArrayList<>();
public void addElement( String input )
{
this.chain.add( input );
}
public void printList()
{
for( String s : this.chain )
{
System.out.println( s );
}
}
public static void main(String args[])
{
Foo x = new Foo();
Foo y = new Foo();
x.addElement( "abc" );
x.addElement( "pqr" );
y.addElement( "lmn" );
y.addElement( "rty" );
x.printList(); //print abc pqr
y.printList(); //print lmn rty
}
}
This should work, from my understanding of what you want. You might wanna initialize ArrayList in constructor - but thats your choice.
Im building a lexical/syntex analyzer for class. The problem I am having is when I try to access my static variable "lexems" or "tokens" from a method besides main they are NULL. When I use them in main (such as the lex.printList method) they are fine and filled with data.
Whats going on???
import java.io.IOException;
import java.util.ArrayList;
public class SyntaxAnalyzer {
public static int pos = 0;
public static ArrayList<String> lexems = new ArrayList<String>();
public static ArrayList<String> tokens = new ArrayList<String>();
public static String nextToken;
public static void main(String[] args) throws IOException {
LexicalAnalysis lex = new LexicalAnalysis();
lex.getFile();
lex.parseText();
ArrayList<String> lexems = lex.getLexems();
lex.printList(lexems);
ArrayList<String> tokens = lex.getTokens();
lex.printList(tokens);
//expr();
lex();
}
static void lex(){
//String lexem = lexems.get(pos);
//System.out.println(lexem);
nextToken = tokens.get(pos);
pos++;
}
}
You are overriding the lexems object with the local one so it is not static variable you are modifying inside main function.
To operate on the static one you should do
/*NOTHING HERE!!*/ lexems = lex.getLexems();
lex.printList(lexems);
...
The same issue with tokens occurs
/*NOTHING HERE!!*/ tokens = lex.getTokens();
lex.printList(tokens);
...
The problems are here:
ArrayList<String> lexems = lex.getLexems();
lex.printList(lexems);
ArrayList<String> tokens = lex.getTokens();
In you main function you do not modify the static variables but local ones (local in the main function).
Just change it to that:
lexems = lex.getLexems();
tokens = lex.getTokens();
You are creating another pair of variables in your main method, which happen to have same names as your static variables, and "overshadow" them within the scope of main method.
To fix it, you should not declare new variables, but initialise the existing ones:
public static void main(String[] args) throws IOException {
LexicalAnalysis lex = new LexicalAnalysis();
lex.getFile();
lex.parseText();
lexems = lex.getLexems();
lex.printList(lexems);
tokens = lex.getTokens();
lex.printList(tokens);
//expr();
lex();
}
This should help make the difference between the scopes used in your code :
public class MyClass{
private static int myInt;
public static void main(String[] args){
int myInt = 6;
printMyInt();
}
static void printMyInt(){ System.out.println(myInt); } // Prints 0 because uses the class field
}
I tried the following code:
constructor = oneClass.getConstructor(new Class[]{String[].class});
return constructor.newInstance(new String[]{"String01","String02"})
(the return Statement return an IllegalArgumentException)
And
Class stringArray = Class.forName("[Ljava.lang.String;");
constructor = oneClass.getConstructor(new Class[]{stringArray})
return constructor.newInstance(new String[]{"String01","String02"})
(the return Statement return an IllegalArgumentException)
How to say that I want to instantiate a constructor with a String[] as argument.
Thank You.
What about this :
constructor = oneClass.getConstructor(String[].class);
return constructor.newInstance(new Object[]{new String[]{"String01","String02"}})
Assuming your constructor is like this :
public class OneClass
{
public OneClass(String[] args)
{
// ...
}
}
Source : Problem with constructing class using reflection and array arguments
Calling newInstance directly with a new String[] confuses it because it is not sure if that new String[] is one arg, or an alternate way to represent the varargs. By assigning it to an Object "abc" below, it definitely tells the compiler that abc (which represents the String array) is one arg, arg0 to be exact, and not a varargs representing multiple arguments.
import java.lang.reflect.Constructor;
public class Test {
public Test(String[] args) {
System.out.println(args);
}
public static void main(String[] args) throws Exception {
Constructor<Test> constructor = Test.class.getConstructor(String[].class);
new Test(new String[]{});
Object abc = new String[]{};
constructor.newInstance(abc);
}
}
I have the following code, and am wondering why null is returned when I run the program and not the actual value? Any help would be appericated.
import java.util.Random;
public class TestCard {
public static String[] possCards = new String[]{"2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A"};
public static String[] possSuits = new String[]{"C", "S", "H", "D"};
public static Random rand = new Random();
static String value;
public static void main(String[] args) {
System.out.println(getcard());
}
public static void card() {
String card = possCards[rand.nextInt(possCards.length)];
String suit = possSuits[rand.nextInt(possSuits.length)];
value = card + suit;
}
public static String getcard(){
return value;
}
}
Because null is the value held by value at the time the program is run.
Why should it be any different if you don't call any of the methods that give value a reference, such as card(), before calling getCard()?
Key thing here is to try to walk through your code mentally step wise to see what it does. Either that or step through your code with a debugger.
You're calling getcard() but never calling card(), so value is never set.
Check the following portion of your code:
public static void main(String[] args) {
System.out.println(getcard()); // printing getCard(),
//but card() isn't called before it!!
}
public static void card() {
String card = possCards[rand.nextInt(possCards.length)];
String suit = possSuits[rand.nextInt(possSuits.length)];
value = card + suit; // assigning value in card()
//but this function needs to get executed
}
You should call the card() function:
public static void main(String[] args) {
card();
System.out.println(getcard());
}
Before calling the getcard() you need to call card() to preparing your calculations.
Your code need to look like below.
public static void main(String[] args) {
card();
System.out.println(getcard());
}
you could also have a static block of code in your TestCard that will initialize the value for you:
static{
card();
}
so you know value to be non null
I'm trying to create a class with static variables, but I'm not sure how to set the variables before runtime. This is what I'm attempting to do...
public class Defaults {
public static String[] abc = new String[2];
public static void functionToExecuteBeforeRuntime{
abc[0] = "a";
abc[1] = "b";
abc[2] = "c";
}
}
It's supposed to set abc using functionToExecuteBeforeRuntime before runtime so other classes can access it with Defaults.abc,however it is never executed. How can I achieve this? Any help appreciated
-oh i'm not sure if this makes a difference but I don't think with andriod I can use the public static main() guy
For that example, you could just initialize it there, like:
public static String[] abc = new String[]{"a", "b", "c"};
For just a general way of doing complex initialization for your static fields, I'm not sure, but I believe Android has Static Initializer Blocks, which work like:
public class Test
{
public static String[] stuff = new String[2];
static
{
stuff[0] = "Hi";
stuff[1] = "Bye";
}
}
Or you could use static functions to do, basically, the same thing.
public class Test
{
public static String[] stuff = initializeStuff();
public static String[] initializeStuff()
{
String[] arr = new String[2];
arr[0] = "Hi";
arr[1] = "Bye";
return arr;
}
}
Put it into a static initialization block of code like so:
private static String[] stuff;
static {
stuff = new String[] {"1", "2"};
}