How to initialize a static SparseArray - java

How can I initialize a static, unmodifiable instance of android.util.SparseArray?

Here is a better way using an anonymous class:
static final SparseIntArray myArray = new SparseIntArray() {
{
append(1, 2);
append(10, 20);
}
};

You cannot do what you are attempting to. At least, not how you are attempting to do it. There is no implementation of SparseArray that is unmodifiable.
However, you could create one. Here's how:
Create a class, say CustomSparseArray<E>, and have it extend SparseArray.
Override all methods that change the elements in the array, and replace them with something like this:
#Override
public void append(int key, E value) {
if (mLocked)
return; // Maybe throw an exception
super.append(key, value);
}
Then, add in a member variable to the class, boolean mLocked = false;.
Next, you need a method like the following:
public void lock() { mLocked = true; }
Lastly, implement your static variable using a method similar to in the other post:
public class Test {
private static final CustomSparseArray<Integer> myArray;
static {
myArray = new CustomSparseArray<Integer>();
myArray.append(1, 1);
myArray.append(2, 5);
myArray.lock();
}
}
Then you have an unmodifiable SparseArray in your static variable myArray.

This works for me:
static final SparseIntArray CMyArray = new SparseIntArray();
static {
CMyArray.append(2, 4);
CMyArray.append(8, 3);
CMyArray.append(255, 1);
}
as per: https://docs.oracle.com/javase/tutorial/java/javaOO/initial.html

Related

Alternative to static blocks without unused variable

As an alternative to static blocks, Oracle docs are suggesting to call a method(s) and the example is using a variable assignment:
public static varType myVar = initializeClassVariable();
The advantage of private static methods is that they can be reused later if you need to reinitialize the class variable.
But if I don't need (and want to avoid unused) extra variable and also return statement in my static block, what is a better way to call static code?
Calling a static method in the constructor is wrong design for executing static code once (constructor can be private for utility class) for static block
public MyClass() {
MyClass.initializeClassVariable();
}
So is the only improvement is reducing variable access level to private ?
private static varType myVar = initializeClassVariable();
Or a better approach is to keep static block and add the method there?
static {
initializeClassVariable();
}
The "alternative to static blocks" is about initializing a single static field.
Example:
class A {
static Map<String, Integer> romans;
static {
romans = new HashMap<>();
romans.put("I", 1);
romans.put("V", 5);
romans.put("X", 10);
}
}
Alternative:
class A {
static Map<String, Integer> romans = initRomans();
private static Map<String, Integer> initRomans() {
Map<String, Integer> r = new HashMap<>();
r.put("I", 1);
r.put("V", 5);
r.put("X", 10);
return r;
}
}
As the article says, with this code you can reset the static field.
public static void resetRomans() {
romans = initRomans();
}
If your code does something else, then the "alternative" isn't applicable, and you write the code in a static initializer block.
class A {
static {
Manager.register(A.class);
}
}

Return a Reference to a Class with Static Methods and Static Fields Without Instantiation

I want to create a wrapper class that calls static methods and member fields from a class that is provided by a library I am unable to view the code.
This is to avoid boilerplate setting code of the global member fields when I need to use a static method in a specific context.
I want to try to avoid creating wrapper methods for each static method.
My question:
Is it possible to return a class with static methods from a method to access just the static methods without instantiating it?
Code is below with comments in-line.
The code is used to demonstrate a change in a static value when the method getMath() is invoked.
I want to avoid the setting of the value before calling the static method.
StaticMath.setFirstNumber(1);
StaticMath.calc(1);
StaticMath.setFirstNumber(2);
StaticMath.calc(1);
I am using the Eclipse IDE and it comes up with Warnings, which I understand, but want to avoid.
I tried searching for something on this subject, so if anyone can provide a link I can close this.
public class Demo {
// Static Methods in a class library I don't have access to.
static class StaticMath {
private static int firstNum;
private StaticMath() {
}
public static int calc(int secondNum) {
return firstNum + secondNum;
}
public static void setFirstNumber(int firstNum) {
StaticMath.firstNum = firstNum;
}
}
// Concrete Class
static class MathBook {
private int firstNum;
public MathBook(int firstNum) {
this.firstNum = firstNum;
}
// Non-static method that gets the class with the static methods.
public StaticMath getMath() {
StaticMath.setFirstNumber(firstNum);
// I don't want to instantiate the class.
return new StaticMath();
}
}
public static void main(String... args) {
MathBook m1 = new MathBook(1);
MathBook m2 = new MathBook(2);
// I want to avoid the "static-access" warning.
// Answer is 2
System.out.println(String.valueOf(m1.getMath().calc(1)));
// Answer is 3
System.out.println(String.valueOf(m2.getMath().calc(1)));
}
}
I'd just wrap it to make for an atomic operation:
public static class MyMath{
public static synchronized int myCalc( int num1 , int num2 ){
StaticMath.setFirstNum(num1);
return StaticMath.calc(num2);
}
}
Drawback: You'll have to make sure, StaticMath is not used avoiding this "bridging" class.
Usage:
int result1 = MyMath.myCalc( 1, 1 );
int result1 = MyMath.myCalc( 2, 1 );
You shouldnt call a static method through an object reference. You should directly use class reference to call a static method like this:
StaticMath.calc(1)
But if you still need it for some reason, you can return null in getMath method, but you will still get warning in Eclipse:
public StaticMath getMath() {
StaticMath.setFirstNumber(firstNum);
return null;
}
I infer that question is not properly asked if the answer is not
StaticMath.calc(1)
Other issue you may be facing due to package visibility to static inner classes. Which is a design choice by the writer of Demo class. If you can mark your classes MathBook and StaticMath public then you can access them like below:
Demo.StaticMath.calc(1);

Why we are not able to create non-static self-referential object in constructor

When I am trying to create an object with self reference in constructor I am getting StackOverflowError.
public class Example1 {
private int i;
private Example1 zero;
public Example1(int i) {
super();
if (i > 0) {
this.i = i;
} else {
this.i = this.zero.i;
}
this.zero = new Example1(i);
}
public int getI() {
return i;
}
But when I do with static reference no error occurs.
public class Example2 {
private int i;
private static final Example2 ZERO = new Example2(0);
public Example2() {
this(ZERO.i);
}
public Example2(int i) {
super();
this.i = i;
}
public int getI() {
return i;
}
Since static object will be initialized while loading the class it is working that I am able to understand.
But what is happening during object creation, Can anyone explain in detail?
Exampel1 creates new instances recursively in the constructor.
The static field will only be created once. That's why example 1 created the overflow and the second does not.
Static modifier implies that whatever you made static is shared among all the objects of that class. Since I believe you want to make something like a "default object" inside each Example1 object, the best way to do it is to make it static. This way, you can create as many Example1 objects as you want (or your memory allows) but every one of them will share the static Example1 zero object.
Non static object here is impossible, because it will otherwise try to create another Example1 object inside the Example1 object you just created, which will of course have another Example1 object in an infinite loop, as other people has already stated.

Setting an array variable being passed to a function

Ok this is a guess a really simple problem which I am having a black out about.... however it is killing my head.
Here is the source:
import java.util.Arrays;
public class InputValues {
public int[] myarrayvar;
public InputValues(int[] myarraypass) {
---- help here
}
public void init() {
---help here
}
public int[] getmyarrayvar() {
return myarrayvar;
}
public void setmyarrayvar(int[] myarraypass) {
this.myarrayvar= mayarraypass;
}
}
I call the this with
InputValues inputValues = new InputValues(myarraypass);
inputValues.init();
myarraypass is of type int[].
Like I said this should be really easy.... but I can't get it to work for some reason....
In case your myarrayvar is public then why would you need a setter and getter. You need them only when your member is inaccessible to the outside world, i.e. it's marked private.
Nest, you can use the following in your constructor for setting the array,
public InputValues(int[] myarraypass) {
this.myarrayvar = new int[myarraypass.length];
System.arraycopy(myarraypass, 0, this.myarrayvar, 0, myarraypass.length );
}
You can try following things:
Change the instance variable access from public to private.
in constructor you can use following line:
this.myarrayvar = myarraypass;
But remember, if myarraypass is modified outside class InputValues, myarrayvar will also be affected.
If you don't want that behavior to occur, you should copy index-by-index.
this.myarrayvar = new int[myarraypass.length];
for(int i=0; i<myarraypass.length;i++)
this.myarrayvar[i] = myarraypass[i];
OR
this.myarrayvar = (int[]) myarraypass.clone();
OR
this.myarrayvar = new int[myarraypass.length];
System.arraycopy(myarraypass, 0, this.myarrayvar, 0, myarraypass.length);

Static Initialization Blocks

As far as I understood the "static initialization block" is used to set values of static field if it cannot be done in one line.
But I do not understand why we need a special block for that. For example we declare a field as static (without a value assignment). And then write several lines of the code which generate and assign a value to the above declared static field.
Why do we need this lines in a special block like: static {...}?
The non-static block:
{
// Do Something...
}
Gets called every time an instance of the class is constructed. The static block only gets called once, when the class itself is initialized, no matter how many objects of that type you create.
Example:
public class Test {
static{
System.out.println("Static");
}
{
System.out.println("Non-static block");
}
public static void main(String[] args) {
Test t = new Test();
Test t2 = new Test();
}
}
This prints:
Static
Non-static block
Non-static block
If they weren't in a static initialization block, where would they be? How would you declare a variable which was only meant to be local for the purposes of initialization, and distinguish it from a field? For example, how would you want to write:
public class Foo {
private static final int widgets;
static {
int first = Widgets.getFirstCount();
int second = Widgets.getSecondCount();
// Imagine more complex logic here which really used first/second
widgets = first + second;
}
}
If first and second weren't in a block, they'd look like fields. If they were in a block without static in front of it, that would count as an instance initialization block instead of a static initialization block, so it would be executed once per constructed instance rather than once in total.
Now in this particular case, you could use a static method instead:
public class Foo {
private static final int widgets = getWidgets();
static int getWidgets() {
int first = Widgets.getFirstCount();
int second = Widgets.getSecondCount();
// Imagine more complex logic here which really used first/second
return first + second;
}
}
... but that doesn't work when there are multiple variables you wish to assign within the same block, or none (e.g. if you just want to log something - or maybe initialize a native library).
Here's an example:
private static final HashMap<String, String> MAP = new HashMap<String, String>();
static {
MAP.put("banana", "honey");
MAP.put("peanut butter", "jelly");
MAP.put("rice", "beans");
}
The code in the "static" section(s) will be executed at class load time, before any instances of the class are constructed (and before any static methods are called from elsewhere). That way you can make sure that the class resources are all ready to use.
It's also possible to have non-static initializer blocks. Those act like extensions to the set of constructor methods defined for the class. They look just like static initializer blocks, except the keyword "static" is left off.
It's also useful when you actually don't want to assign the value to anything, such as loading some class only once during runtime.
E.g.
static {
try {
Class.forName("com.example.jdbc.Driver");
} catch (ClassNotFoundException e) {
throw new ExceptionInInitializerError("Cannot load JDBC driver.", e);
}
}
Hey, there's another benefit, you can use it to handle exceptions. Imagine that getStuff() here throws an Exception which really belongs in a catch block:
private static Object stuff = getStuff(); // Won't compile: unhandled exception.
then a static initializer is useful here. You can handle the exception there.
Another example is to do stuff afterwards which can't be done during assigning:
private static Properties config = new Properties();
static {
try {
config.load(Thread.currentThread().getClassLoader().getResourceAsStream("config.properties");
} catch (IOException e) {
throw new ExceptionInInitializerError("Cannot load properties file.", e);
}
}
To come back to the JDBC driver example, any decent JDBC driver itself also makes use of the static initializer to register itself in the DriverManager. Also see this and this answer.
I would say static block is just syntactic sugar. There is nothing you could do with static block and not with anything else.
To re-use some examples posted here.
This piece of code could be re-written without using static initialiser.
Method #1: With static
private static final HashMap<String, String> MAP;
static {
MAP.put("banana", "honey");
MAP.put("peanut butter", "jelly");
MAP.put("rice", "beans");
}
Method #2: Without static
private static final HashMap<String, String> MAP = getMap();
private static HashMap<String, String> getMap()
{
HashMap<String, String> ret = new HashMap<>();
ret.put("banana", "honey");
ret.put("peanut butter", "jelly");
ret.put("rice", "beans");
return ret;
}
There are a few actual reasons that it is required to exist:
initializing static final members whose initialization might throw an exception
initializing static final members with calculated values
People tend to use static {} blocks as a convenient way to initialize things that the class depends on within the runtime as well - such as ensuring that particular class is loaded (e.g., JDBC drivers). That can be done in other ways; however, the two things that I mention above can only be done with a construct like the static {} block.
You can execute bits of code once for a class before an object is constructed in the static blocks.
E.g.
class A {
static int var1 = 6;
static int var2 = 9;
static int var3;
static long var4;
static Date date1;
static Date date2;
static {
date1 = new Date();
for(int cnt = 0; cnt < var2; cnt++){
var3 += var1;
}
System.out.println("End first static init: " + new Date());
}
}
It is a common misconception to think that a static block has only access to static fields. For this I would like to show below piece of code that I quite often use in real-life projects (copied partially from another answer in a slightly different context):
public enum Language {
ENGLISH("eng", "en", "en_GB", "en_US"),
GERMAN("de", "ge"),
CROATIAN("hr", "cro"),
RUSSIAN("ru"),
BELGIAN("be",";-)");
static final private Map<String,Language> ALIAS_MAP = new HashMap<String,Language>();
static {
for (Language l:Language.values()) {
// ignoring the case by normalizing to uppercase
ALIAS_MAP.put(l.name().toUpperCase(),l);
for (String alias:l.aliases) ALIAS_MAP.put(alias.toUpperCase(),l);
}
}
static public boolean has(String value) {
// ignoring the case by normalizing to uppercase
return ALIAS_MAP.containsKey(value.toUpper());
}
static public Language fromString(String value) {
if (value == null) throw new NullPointerException("alias null");
Language l = ALIAS_MAP.get(value);
if (l == null) throw new IllegalArgumentException("Not an alias: "+value);
return l;
}
private List<String> aliases;
private Language(String... aliases) {
this.aliases = Arrays.asList(aliases);
}
}
Here the initializer is used to maintain an index (ALIAS_MAP), to map a set of aliases back to the original enum type. It is intended as an extension to the built-in valueOf method provided by the Enum itself.
As you can see, the static initializer accesses even the private field aliases. It is important to understand that the static block already has access to the Enum value instances (e.g. ENGLISH). This is because the order of initialization and execution in the case of Enum types, just as if the static private fields have been initialized with instances before the static blocks have been called:
The Enum constants which are implicit static fields. This requires the Enum constructor and instance blocks, and instance initialization to occur first as well.
static block and initialization of static fields in the order of occurrence.
This out-of-order initialization (constructor before static block) is important to note. It also happens when we initialize static fields with the instances similarly to a Singleton (simplifications made):
public class Foo {
static { System.out.println("Static Block 1"); }
public static final Foo FOO = new Foo();
static { System.out.println("Static Block 2"); }
public Foo() { System.out.println("Constructor"); }
static public void main(String p[]) {
System.out.println("In Main");
new Foo();
}
}
What we see is the following output:
Static Block 1
Constructor
Static Block 2
In Main
Constructor
Clear is that the static initialization actually can happen before the constructor, and even after:
Simply accessing Foo in the main method, causes the class to be loaded and the static initialization to start. But as part of the Static initialization we again call the constructors for the static fields, after which it resumes static initialization, and completes the constructor called from within the main method. Rather complex situation for which I hope that in normal coding we would not have to deal with.
For more info on this see the book "Effective Java".
So you have a static field (it's also called "class variable" because it belongs to the class rather than to an instance of the class; in other words it's associated with the class rather than with any object) and you want to initialize it. So if you do NOT want to create an instance of this class and you want to manipulate this static field, you can do it in three ways:
1- Just initialize it when you declare the variable:
static int x = 3;
2- Have a static initializing block:
static int x;
static {
x=3;
}
3- Have a class method (static method) that accesses the class variable and initializes it:
this is the alternative to the above static block; you can write a private static method:
public static int x=initializeX();
private static int initializeX(){
return 3;
}
Now why would you use static initializing block instead of static methods?
It's really up to what you need in your program. But you have to know that static initializing block is called once and the only advantage of the class method is that they can be reused later if you need to reinitialize the class variable.
let's say you have a complex array in your program. You initialize it (using for loop for example) and then the values in this array will change throughout the program but then at some point you want to reinitialize it (go back to the initial value). In this case you can call the private static method. In case you do not need in your program to reinitialize the values, you can just use the static block and no need for a static method since you're not gonna use it later in the program.
Note: the static blocks are called in the order they appear in the code.
Example 1:
class A{
public static int a =f();
// this is a static method
private static int f(){
return 3;
}
// this is a static block
static {
a=5;
}
public static void main(String args[]) {
// As I mentioned, you do not need to create an instance of the class to use the class variable
System.out.print(A.a); // this will print 5
}
}
Example 2:
class A{
static {
a=5;
}
public static int a =f();
private static int f(){
return 3;
}
public static void main(String args[]) {
System.out.print(A.a); // this will print 3
}
}
If your static variables need to be set at runtime then a static {...} block is very helpful.
For example, if you need to set the static member to a value which is stored in a config file or database.
Also useful when you want to add values to a static Map member as you can't add these values in the initial member declaration.
It is important to understand that classes are instantiated from java.class.Class during runtime. That is when static blocks are executed, which allows you to execute code without instantiating a class:
public class Main {
private static int myInt;
static {
myInt = 1;
System.out.println("myInt is 1");
}
// needed only to run this class
public static void main(String[] args) {
}
}
The result is myInt is 1 printed to the console.
As supplementary, like #Pointy said
The code in the "static" section(s) will be executed at class load
time, before any instances of the class are constructed (and before
any static methods are called from elsewhere).
It's supposed to add System.loadLibrary("I_am_native_library") into static block.
static{
System.loadLibrary("I_am_a_library");
}
It will guarantee no native method be called before the related library is loaded into memory.
According to loadLibrary from oracle:
If this method is called more than once with the same library name,
the second and subsequent calls are ignored.
So quite unexpectedly, putting System.loadLibrary is not used to avoid library be loaded multi-times.
static block is used for any technology to initialize static data member in dynamic way,or we can say for the dynamic initialization of static data member static block is being used..Because for non static data member initialization we have constructor but we do not have any place where we can dynamically initialize static data member
Eg:-class Solution{
// static int x=10;
static int x;
static{
try{
x=System.out.println();
}
catch(Exception e){}
}
}
class Solution1{
public static void main(String a[]){
System.out.println(Solution.x);
}
}
Now my static int x will initialize dynamically ..Bcoz when compiler will go to Solution.x it will load Solution Class and static block load at class loading time..So we can able to dynamically initialize that static data member..
}
static int B,H;
static boolean flag = true;
static{
Scanner scan = new Scanner(System.in);
B = scan.nextInt();
scan.nextLine();
H = scan.nextInt();
if(B < 0 || H < 0){
flag = false;
System.out.println("java.lang.Exception: Breadth and height must be positive");
}
}

Categories

Resources