18 lut 2010

ArrayList []


import java.util.ArrayList;

public class Test {
public static void main(String[] args) {
ArrayList array = new ArrayList();
array[0]="Hello world";
System.out.println(array[0]);
}
}


Nie ma operatora [] w listach!!

Static


// A.java
public class A {
private final int a = 10;
public static String b = "ClassA";
protected long c;
}

// B.java
public class B extends A {
public static String b = "ClassB";
private int d = 1;

public static void test() {
...
}
}




Z metod statycznych ma się tylko dostęp do zmiennych statycznych!

Pytanie: Do jakich zmiennych mam dostęp w B.test() ??

Cast


@Test
public void testCastowania(){

float _45f=45.0f;
char $='\u0000';
//!$=$*$; //promowane do int!!
$=(char)($*$); //poprawnie
//! $=-$; także int

//_45f=_45f/3;
//assertTrue(_45f==15); //pass

//porównanie inta z floatem

int _45i=45;

assertTrue(_45f==_45i);//pass
assertTrue(_45i==_45f);//pass

//inne promowania
long _45l=_45i; //autmoatyczne promowanie

// możliwa utrata informacji ->
//błąd kompilacji
//!_45i=_45l;

_45i=(int)_45l; //poprawnie!

float a12=(float)1/3;
prn(a12); //0.33333
int jestemIntem=(int)a12;
prn(jestemIntem); //0
//a12=1.1; //daje daoubla
a12=1.6f; //ok
jestemIntem=(int)a12;
prn(jestemIntem); //1 (zaokragla w dół)

}

Skracanie łańcucha logicznego


/**
* Pomocnicza
* @param test
* @return
*/
private boolean test(boolean test){
prn(test);
return test;
}

@Test
public void testLancuchaLogicznego(){

if(test(true) || test(true)){ } //true
if(test(true) && test(true)){ } //true true
if(test(false) || test(true)){ } //false true
if(test(false) && test(true)){ } //FFALSE
prn("ZŁOŻONE:");

if((test(false))||((test(false))&&(test(true)))){}
//false false

}

Inkrementacja dekrementacja


@Test
public void testKrementacji(){

/* Test 1*/
int i=5;
int j=i++;
int k=i++ + i;

assertEquals(5, j);//pass
assertEquals(13, k);//pass

/*Test2*/
i=5;
j=i--;
k=i++;
int l=i++ + --i;
assertEquals(5, j);//pass
assertEquals(4, k);//pass
assertEquals(10, l);//pass

/*Test3*/
i=5;
j=--i +i++ + i++;
assertTrue(13==j); //pass
assertTrue(6==i); //pass
}

Test print


//System.out.println(...)
@Test
public void testPrinta(){

float x=10/3; //x=3.0
float y= (float)10/3; //y=3.3333333
float z= 10/(float)3; //y=3.3333333

prn(1+2+2+"ok"); //5ok
prn("ok" + new String("nie")); //oknie
prn("OK"+(3-1));//ok2
//!prn("ok"+9-6); //nie da się
}

Referencje-test


@Test
public void testReferencji(){

String a=null;
String b=null;
b=a;
a=new String("ok");
// assertEquals(a, b); //b=null!
b=a;
assertEquals(a, b);//a równe b
assertTrue(a.equals(b)); //pass
assertTrue(a==b);//pass
}