Layout class는 View widget들을 group화하여

배치하기 위한 용도로사용되는 ViewGroup이다

 

1. LinearLayout

여러 View widget들을 가로또는 세로방향으로 나열할때 사용하는 Layout class이다

widget의 크기와 관계없이 한방향으로 stacked형태로 표시된다

weight 기능을 이용해 View widget간의 상대적인값으로 크기를 설정할수있다 

 

2. RelativeLayout

View widget들이 서로간의 상대적배치관계에따라 화면에 표시될위치가 결정된다

부모 Layout class 자체가 상대적 위치의 기준점으로 사용될수도있다

상대적인 배치 기준점을 지정하지 않는다면 중첩되어 표시된다.

 

3. FramLayout

하나의 자식 View widget만을 표시할때 사용되는 layout class이다

여러 View widget을 추가할경우 중첩되며

마지막에 추가된 View widget이 상위에표시된다

 

4. TableLayout

View widget들을 table(행과 열)로 나누어 표시하는 Laout class이다

TableRow class를 이용해 행을추가하고 View widget을 추가하면 table형태로 표시된다

 

5. ListView와 GridView

View widget을 내용만 달리하여 반복적으로 표시할경우 사용될수있다

'android studio' 카테고리의 다른 글

AdapterView(ListView)  (0) 2019.08.10
view에 도형, 텍스트 그리기  (0) 2019.08.10
Button, RadioButton, CheckBox, ImageView, ImageButton  (0) 2019.08.10
text view  (0) 2019.08.09
Custom ListView  (0) 2019.08.07

1. activity_main.xml

//title과 list부분의 전체적인 style을 설정한다

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http:/

/schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">

<TextView
android:id="@+id/tv01"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:text = "jusung"
android:textSize="30dp"
android:textStyle="bold"/>
<ListView
android:id="@+id/listView01"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="9">
</ListView>
</LinearLayout>

 

2. item_style.xml

//list부분에서 item내부의 style을 설정한다

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent">

<ImageView
android:id="@+id/icon"
android:layout_width="80dp"
android:layout_height="80dp"/>
<TextView
android:id="@+id/title"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:textStyle="bold"
android:padding="10dp"
android:paddingTop="30dp"/>
<TextView
android:id="@+id/comment"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:paddingLeft="20dp"
android:paddingTop="30dp"/>
<Button
android:id="@+id/btn_select"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text = "select"/>
</LinearLayout>

 

3. Data.java

//data를 객체를 활용하기위한 class

package com.example.myapplication;

public class Data {
private int icon;
private String title;
private String comment;

public Data(int icon, String title, String comment){
this.icon = icon;
this.title = title;
this.comment = comment;
} //객체를 생성하기위한 생성자

public int getIcon(){
return icon;
}
public String getTitle(){
return title;
}
public String getComment(){
return comment;
}
}

 

4. MainActivity.java

//data를 가져오기위한 ArrayList생성하고 data를 추가한다

//Data class에 생성자를이용해 객체를 생성하고 add method를이용해 배열에 추가시킨다

package com.example.myapplication;

import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ListView;
import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

private ArrayList<Data> data = null;
private CustomAdapter cAdapter = null;
private ListView listView = null;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

data = new ArrayList<Data>();

data.add(new Data(R.drawable.semo, title: "hehehe", comment: "hohohoho"));
data.add(new Data(R.drawable.semo, title: "hehehe", comment: "hohohoho"));
data.add(new Data(R.drawable.semo, title: "hehehe", comment: "hohohoho"));
data.add(new Data(R.drawable.semo, title: "hehehe", comment: "hohohoho"));
data.add(new Data(R.drawable.semo, title: "hehehe", comment: "hohohoho"));
data.add(new Data(R.drawable.semo, title: "hehehe", comment: "hohohoho"));

cAdapter = new CustomAdapter( context: this, R.layout.item_style, data);

//item_style의 layout을 설정하고 위에만들어논 data로 cAdapter를 생성한다

listView = findViewById(R.id.listView01);

//listView를 id를통해 가져온다
listView.setAdapter(cAdapter);

//listView에 Adapter로 setting한다
}
}

5.itemView.java

//item_style에 입력된 data를 memory로 loading하기위해서

//객체화하는과정이필요한데 이를 inflation이라고한다

//item_style에 정의된 style에 data를 가져와 세팅시킨다

package com.example.myapplication;

import android.content.Context;
import android.view.LayoutInflater;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

public class itemView extends LinearLayout{
private ImageView mIcon;
private TextView mTitle;
private TextView mComment;

//생성자 생성
public itemView(Context context, Data data){
super(context);

//인플레이션: 메모리에 올려 객체화하는것
LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
inflater.inflate(R.layout.item_style, root: this, attachToRoot: true);
//inflate method를 이용해 item_style를 parameter로 불러오고
//root element를 linearlayout으로 설정하고 root를 포함한다에 true값을 설정

//set Icon
mIcon = findViewById(R.id.icon);
mIcon.setImageResource(data.getIcon());

//set Title
mTitle = findViewById(R.id.title);
mTitle.setText(data.getTitle());

//set Comment
mComment = findViewById(R.id.comment);
mComment.setText(data.getComment());
}//Data class에 getIcon method를 이용해 return값을 받아오고
}//Set함수를 이용해 세팅시킨다

 

6. CustomAdapter.jave

//추상class BaseAdapter을 상속받아서

//getView, getCount method를 이용해 CustomAdapter를 만든다

//getCount는 item의 개수를 return해주는 역할을한다

//item은 item index를 통해 구분을 해주는데

//indexr값을 구하려면 getCount를 통해 전체 item의 개수를 알아야한다

//getView는 item에 보이는 View와 관련이있다

package com.example.myapplication;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.ArrayList;

public class CustomAdapter extends BaseAdapter {
private Context mContext = null;
private int layout = 0;
private ArrayList<Data> mData = null;
private LayoutInflater inflater = null;

//data를 입력하기위한 ArrayList를 만든다

public CustomAdapter(Context context, int layout, ArrayList<Data> mData){
this.mContext = context;
this.layout = layout;
this.mData = mData;
this.inflater = (LayoutInflater)context.getSystemService(context.LAYOUT_INFLATER_SERVICE);
} //생성자 생성


public int getCount(){
return mData.size();
} //index를 얻어오기위해 item의 개수를 return
public Object getItem(int position){
return mData.get(position).getTitle();
} //position은 item의 index위치를 가져오기위한 parameter이다
public long getItemId(int position){
return position;
} //position을 매개변수로 index값을 가져온다
public View getView(int position, View convertView, ViewGroup parent){
if(convertView == null){
convertView = inflater.inflate(this.layout, parent, attachToRoot: false);
}//만들어진 item view를 convertView를 통해 불러온다.

//하나만 있으면되기때문에 null인경우를 확인후 생성한다
ImageView ico = convertView.findViewById(R.id.icon);
TextView title = convertView.findViewById(R.id.title);
TextView comment = convertView.findViewById(R.id.comment);
Button btn_select = convertView.findViewById(R.id.btn_select);

//만들어논 item_style(image, text, text, button) 을 convertView를통해 불러온다

ico.setImageResource(mData.get(position).getIcon());
title.setText(mData.get(position).getTitle());
comment.setText(mData.get(position).getComment());

//불러온 객체를 position을 활용하여 setting 해줘야한다

if((position%2) == 1){
convertView.setBackgroundColor(0x800000ff);
}else{
convertView.setBackgroundColor(0x200000ff);
} //item들에 색깔을지정하여 구분하기쉽게한다
return convertView;
}
}

 

Result

inflation을 itemView에 설정할경우

MainActivity.java, itemView.java, CustomAdapter.java 파일을

아래와같이 변경한다

4. MainActivity.java

package com.example.myapplication;

import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ListView;
import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

private ArrayList<Data> data = null;
private CustomAdapter cAdapter = null;
private ListView listView = null;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

cAdapter = new CustomAdapter(context: this);
cAdapter.addItem(new Data(R.drawable.semo, title: "hehehe", comment: "hohohoho"));
cAdapter.addItem(new Data(R.drawable.semo, title: "hehehe", comment: "hohohoho"));
cAdapter.addItem(new Data(R.drawable.semo, title: "hehehe", comment: "hohohoho"));
cAdapter.addItem(new Data(R.drawable.semo, title: "hehehe", comment: "hohohoho"));
cAdapter.addItem(new Data(R.drawable.semo, title: "hehehe", comment: "hohohoho"));
cAdapter.addItem(new Data(R.drawable.semo, title: "hehehe", comment: "hohohoho"));

listView = findViewById(R.id.listView01);
listView.setAdapter(cAdapter);
}
}

 

5.itemView.java

package com.example.myapplication;

import android.content.Context;
import android.view.LayoutInflater;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

public class itemView extends LinearLayout{
private ImageView mIcon;
private TextView mTitle;
private TextView mComment;

//생성자 생성
public itemView(Context context, Data data){
super(context);

//인플레이션: 메모리에 올려 객체화하는것
LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
inflater.inflate(R.layout.item_style, this, true);
//inflate method를 이용해 item_style를 parameter로 불러오고
// root element를 linearlayout으로 설정하고 root를 포함한다에 true값을 설정

//set Icon
mIcon = findViewById(R.id.icon);

//set Title
mTitle = findViewById(R.id.title);

//set Comment
mComment = findViewById(R.id.comment);
//Data class에 getIcon method를 이용해 return값을 받아오고
//Set함수를 이용해 세팅시킨다
}
public void setIcon(int icon){mIcon.setImageResource(icon);};
public void setTitle(String data){mTitle.setText(data);};
public void setComment(String data){mComment.setText(data);};
//Data class에 get mothod를 setting하는 작업
}

6. CustomAdapter.jave

package com.example.myapplication;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.ArrayList;

public class CustomAdapter extends BaseAdapter {
private Context mContext = null;
private ArrayList<Data> mData = new ArrayList<Data>();

public CustomAdapter(Context context){
this.mContext = context;
}

//item 추가위한 method
public void addItem(Data data){
mData.add(data);
} //MainActivity에서 data를 추가시키기위한 method

//item의 개수를 return
public int getCount(){
return mData.size();
}
public Object getItem(int position){
return mData.get(position).getTitle();
}
public long getItemId(int position){
return position;
}
public View getView(int position, View convertView, ViewGroup parent){
itemView itemView;
if(convertView == null){
itemView = new itemView(mContext, mData.get(position));
//position을 이용해 data를가져오고 itemView를 생성한다
}else{
itemView = (itemView)convertView;
} //이미 있을경우 itemView를 (itemView)형변환을해준후
// 기존의 convertView로 대채해준다

itemView.setIcon(mData.get(position).getIcon());
itemView.setTitle(mData.get(position).getTitle());
itemView.setComment(mData.get(position).getComment());
//position을 활용하여 itemView에 set method와
// Data class에 get mothod를이용해 세팅한다

if((position%2) == 1){
itemView.setBackgroundColor(0x800000ff);
}else{
itemView.setBackgroundColor(0x200000ff);
}
return itemView;
}
}

'android studio' 카테고리의 다른 글

AdapterView(ListView)  (0) 2019.08.10
view에 도형, 텍스트 그리기  (0) 2019.08.10
Button, RadioButton, CheckBox, ImageView, ImageButton  (0) 2019.08.10
text view  (0) 2019.08.09
android layout  (0) 2019.08.07

Collection FrameWork는 값을 담을수있는 그릇을 의미한다
list는 순서를 유지하고 중복을허용한다
set은 순서를 유지하지 않고 중복을 허용하지 않는다

 

//public class
//main
String [] arr = new String[2];
arr[0] = "apple";
arr[1] = "orange";
arr[2] = "grape"; //배열의 크기가 2 이므로 error가 생긴다

for(int i=0;i<arr.length;i++) {
System.out.println(arr[i]);
} //일반적인 배열을 이용하는방법
--------

import java.util.ArrayList;

//public class
//main 
ArrayList al = new ArrayList();
al.add("apple");
al.add("orange");
al.add("grape"); 

//add란 method를 이용해 data를 입력한다

//data를 추가한만큰 배열크기가 증가한다 

//ArrayList는 Object type으로 값을 저장하기때문에

//모든 data type을 입력할수있다


for(int i=0;i<al.size();i++) {
String str = (String)al.get(i); 

System.out.println(str);

//ArrayList 는 size를 이용해 크기를 확인하고

//get이란 method를 이용해 값을 불러온다

//자식type으로 부모type의 data를 가져올때 형변환을해줘야한다

-------

import java.util.ArrayList;

//public class
//main 
ArrayList<String> al = new ArrayList<String>(); 

//generic을 이용해 String type 의 ArrayList를 만든다
al.add("apple"); 
al.add("orange"); 
al.add("grape"); 


for(int i=0;i<al.size();i++) { 
String str = al.get(i); 

System.out.println(str);

//generic을 이용할경우 형변환을 안해줘도된다

-----------

import java.util.ArrayList;

import java.util.Iterator;

import java.util.HashSet;

//public class

//main
ArrayList<String> al = new ArrayList<String>();
//ArrayList를 Collection으로 바꿔도 부모형이기때문에 문제가없다
al.add("first");
al.add("second");
al.sdd("third");
al.add("third");//중복이 가능하다

Iterator ai = al.iterator(); //Iterator은 collection에 접근하기위한 객체이다
while(ai.hasNext()) { 
System.out.println(ai.next()); 
} //순서를 유지하면서 중복된 data도 출력한다

HashSet hs = new HashSet();
//HashSet을 Collection으로 바꿔도 부모형이기때문에 문제가없다
hs.add("first");
hs.add("second");
hs.add("third");
hs.add("third"); //중복이 불가능하다

Iterator hi = hs.iterator();
while(hi.hasNext()) {
System.out.prinln(hi.next());
//순서가 유지되지않고 중복된 data를 허용하지 않는다

 

//Iterator은 hasNext, next, remove라는 3개의 method를 가지고있다 
//hasNext: 접근가능요소를 점검하고 true,false값을 반환한다 
//next: true값으로 읽어올 요소가 있다면 가져온다 
//remove는 next다음 요소를 지우는데 사용된다 
-----------

import java.util.HashSet;

//public class

//main
HashSet<String> A = new HashSet<String>();
A.add("a");
A.add("b");
A.add("c");

HashSet B = new HashSet();
B.add("c");
B.add("d");
B.add("e");

HashSet C = new HashSet();
C.add("a");
C.add("b");

A.containsAll(B); //containsAll method는 부분집합인경우  true값을 반환한다
System.out.println(A.containsAll(B)); //false값이 나온다
System.out.println(A.containsAll(C)); //true값이 나온다

A.addAll(B); //A에 중복된값을 제외한 B값을 더해준다(합집합), 출력시 abcde값 모두가 출력된다
A.retainAll(B): //중복된값을 출력(교칩합), 출력시 c값이 출력된다
A.removeAll(B): //A에 중복된 B값을 제외한다(차집합), 출력시 ab출력
Iterator hi = A.iterator();
while(hi.hasNext()) {
System.out.println(hi.next());
} //hasNext로 각요소에 접근해서 next로 가져온다
--------

import java.util.HashMap;

import java.util.Set;

import java.util.Set;

//public class
//main
//Map은 key와 value의 값으로 구성되있는데

//key값은 중복되어선안되지만 value값은 중복을 허용한다


HashMap<String, String> tel = new HashMap<String, Integer>();

//put method를 이용하여 data를 입력한다
tel.put("seoul", "01");  
tel.put("busan", "02");
tel.put("daegu", "03");

 

//data를 불러오기위해 get(key) 을 이용한다
System.out.println(tel.get("seoul"));  
System.out.println(tel.get("busan"));
System.out.println(tel.get("daegu"));

 

//Map class에 각각의 key,value값을 entry 라고하고 이를 Entry class라고한다 

//Map 이란 interface안에 entrySet method를 이용해서

//entry객체로 set을 구성하여 iterator로 접근할수있다

//Entry class에는 Map에 접근하기위해 getKey,getValue method가 존재한다
Set set = tel.entrySet(); //set을 만들면 iterator를 이용할수있다
Iterator it = set.iterator(); 
while(it.hasNext()) {
Map.Entry e = (Map.Entry)it.next(); //entry가 Object type이기때문에 형변환을 해줘야한다
System.out.println(e.getValue()+e.getKey()); //entry에 method를 이용해 정보를 가져온다
}

//generic을 이용해 미리 type을 설정할수있다
Set<Map.Entry<String, String>> set = tel.entrySet();  
Iterator<Map.Entry<String, String>> it = set.iterator(); 
while(it.hasNext()) {
Map.Entry e = it.next(); 

//미리 type이 설정되었기때문에 형변환을 해줄필요가 없다
System.out.println(e.getValue()+e.getKey());
}
-------------

//public class
//main
HashMap<String, String> tel = new HashMap<String, Integer>();
tel.put("seoul", "01");
tel.put("busan", "02");
tel.put("daegu", "03");

Set<Map.Entry<String, String>> set = tel.entrySet();

for(Map.Entry<String, String> e :set) {  
System.out.println(e.getValue()+e.getKey());
} //Map.Entry<String, String> type으로 set data를 e에 가져온다

'java' 카테고리의 다른 글

Generic  (0) 2019.08.04
이넘클래스(enum class)  (0) 2019.08.03
wrapper class  (0) 2019.08.03
Object class(toString(), Equals(), hashCode())  (0) 2019.08.03
예외처리(Exception)  (0) 2019.08.03

generic이란 class 내부에서 사용할 data type을 외부에서 지정하는 방법

//class Demo
public T data; 
//T type 의 data변수 선언, 꼭 T를 쓸필요는없다.
//main
Demo<String> d1 = new Demo<String>();
Demo<Integer> d2 = new Demo<Integer>();

//data type이 정해져있지않은 class를 이용해

//객체를 생성하면서 data type을 정한다
-----

//일반적인 class 사용하는 방법
//class Demo
public Integer data;
public void setData(Integer data) {
this.data = data;
}
public Integer getData() {
return data;
}

//public class
//main
Demo d1 = new Demo();

Integer ing = new Integer(100);
d1.setData(ing);
System.out.println(d1.getData());
------
//class GenericDemo
public T data;
public void setData(T data) {
this.data = data;
}
public T getData() {
return data;
}

//public class
//main
GenericDemo<Integer> gd = new GenericDemo<Integer>();
gd.setData(new Integer(200));
System.out.println(gd.getData());

//data type을 class가 아닌 여기서 설정할수있다

GenericDemo<String> gd1 = new GenericDemo<String>();
gd1.setData("hello");
System.out.println(gd1.getData());

//하나의 class로 여러 data type을 만들수있어서 효율적이다
-------
//class StudentData 
public String name;
StudentData(String name){
this.name = name;
} //생성자 생성
public String toString() {
return name;
}//주소값이 출력되기때문에 overriding해주거나 

//(p1.data.name)형태로 출력해줘야한다
//class Person <T,E>
public T data;
public E id;
Person(T data, E id){
this.data = data;
this.id = id;
} //생성자 생성

//generic class를 복수의 type으로 사용할경우 참조형을 사용해야한다

//public class

//main
Person<StudentData, Integer> p1 = 

new Person<StudentData, Integer> (new StudentData("jusung"), new Integer(20150000));
//person의 두개의 유형을 설정하고 객체를 생성한다

//복수의 type을 사용할경우 Reference type(참조형)만 가능하다 
System.out.println(p1.data+p1.id);

//data의 경우 주소값이 출력이되기때문에 toString method를 overriding해줘야한다
-------

//class StudentData 
public String name; 
StudentData(String name){ 
this.name = name; 
}
public String toString() { 
return name; 
}
//class Person <T,E>
public T data; 
public E id; 
Person(T data, E id){ 
this.data = data; 
this.id = id; 
} 

public <T> void getInfo(T data) { 
System.out.println(data); 
} //T type의 매개변수를받아서 method에 사용할수있다

//public class

//main 
Person p1 = new Person (new StudentData("jusung"), new Integer(20150000)); 
//두개의 매개변수를 이용해 type을 알수있기때문에

//<StudentData, Integer> 생략해줄수있다
System.out.println(p1.data+p1.id);

//toString을 overriding해줘서 사용하면된다


p1.<StudentData> getInfo(new StudnetData("jusung")); 


StudentData sd = new StudentData("jusung");
p1.getInfo(sd); //sd의 type을 알수있기때문에 generic type을 생략해도된다
---------

//Generic 제한

//class Data
public String getData() {
return "people data";
}

//class StudentData extends Data

public String name; 
StudentData(String name){ 
this.name = name; 
}
public String toString() { 
return name; 
}
//class Person <T extends Data>

//T를 Data의 class나 Data의 자식 class인

//StudentData만을 사용하겠다는뜻이다

public T data; 
Person(T data){ 
this.data = data; 
} 

public <T> void getInfo(T data) { 
System.out.println(data); 
} 

//public class

//main 

Person p1 = new Person("jusung");

----------

//interface 제한

//interface Data
int getData();

 

//class StudentData implements Data

public String name; 
StudentData(String name){ 
this.name = name; 
}

 

public int getData(){

return 20140002;

}//getData의 method를 overriding을 해준다


public String toString() { 
return name; 
}
//class Person <T extends Data>

//T를 Data의 interface나 Data class를 implements한

//StudentData만을 사용하겠다는뜻이다

 

public T data; 
Person(T data){ 
this.data = data; 
} 

public <T> void getInfo(T data) { 
System.out.println(data); 
} 

//public class

//main 

StudentData sd = new StudentData("jusung")

Person p1 = new Person(sd);

p1.getInfo(sd); //jusung이 출력된다

'java' 카테고리의 다른 글

Colletions framework(ArrayList, HashSet)  (0) 2019.08.04
이넘클래스(enum class)  (0) 2019.08.03
wrapper class  (0) 2019.08.03
Object class(toString(), Equals(), hashCode())  (0) 2019.08.03
예외처리(Exception)  (0) 2019.08.03

enumeration class는 열거형 클래스로 연관된 상수들의 집합이다
class 의 일종으로 생성자를 가질수있지만 접근제어자는 private형만 가능하다 
enum class도 일반클래스와 마찬가지로 컴파일할때 자동으로 생성자를만들어주지만
private이기때문에 생성자를 통하여 객체를 생성할수는없다
enum class 의 values() method를 호출하면 
enum class내에 선언되있는 모든 상수를 리턴한다.

 

//public class

public static final int PLATINUM_MEMBER = 1;  
public static final int LOYAL_MEMBER = 2;
public static final int GOLD_MEMBER = 3;  
public static final int SILVER_MEMBER = 4; 

//finall로 상수화시켜 더쉽게 이해할수있게한다

//상수가 많아질경우 복잡해질수있다

//main

int grade = GOLD_MEMBER; 
switch(grade) { 

case PLATINUM_MEMBER: 
System.out.println(30+"% discount"); 
break; 
case LOYAL_MEMBER: 
System.out.println(20+"% discount"); 
break; 
case GOLD_MEMBER: 
System.out.println(10+"% discount"); 
break; 
case SILVER_MEMBER: 
System.out.println(5+"% discount"); 
break; 

//이와같이 개발자 입장에서 이해하기쉽다

----------

interface A{ 
int PLATINUM_MEMBER = 1,LOYAL_MEMBER = 2,GOLD_MEMBER = 3,SILVER_MEMBER = 4; 
//상수가 많을경우 interface를 만들어서 더 단순하게 쓸수있다

//불러올때 앞에 interface명을 붙여줘야한다. ex(A.GOLD_MEMBER;)  

//public class

//main
int grade = A.GOLD_MEMBER; 
switch(grade) { 

case A.PLATINUM_MEMBER: 
System.out.println(30+"% discount"); 
break; 
case A.LOYAL_MEMBER: 
System.out.println(20+"% discount"); 
break; 
case A.GOLD_MEMBER: 
System.out.println(10+"% discount"); 
break; 
case A.SILVER_MEMBER: 
System.out.println(5+"% discount"); 
break; 

-------------

interface A{ 
int PLATINUM_MEMBER = 1,LOYAL_MEMBER = 2,GOLD_MEMBER = 3,SILVER_MEMBER = 4; 
//상수가 많을경우 interface를 만들어서 더 단순하게 쓸수있다

interface B{ 
int PLATINUM_MEMBER = 1,LOYAL_MEMBER = 2,GOLD_MEMBER = 3,SILVER_MEMBER = 4; 
//불러올때 앞에 interface명을 붙여줘야한다. ex(B.GOLD_MEMBER;) 

//A, B 두회사가 있을시 등급은 4등급으로 같지만 할인율이 다를수있다

//public class

//main

if(A.PLATINUM_MEMBER == B.PLATINUM_MEMBER) { 
System.out.println(" A,B의 할인율은 같다") 
//기본형인 int형을 비교하기때문에 error가 발생하지않지만

//runtime중 error가 발생할수있기 때문에 좋은방법이 아니다.
-------------

//interface내의 각각의 상수를 class로 설정할수있다

class A{ 
public static final A PLATINUM_MEMBER = new A(); 
public static final A LOYAL_MEMBER = new A(); 
public static final A GOLD_MEMBER = new A(); 
public static final A SILVER_MEMBER = new A(); 
} 
class B{ 
public static final B PLATINUM_MEMBER = new B(); 
public static final B LOYAL_MEMBER = new B(); 
public static final B GOLD_MEMBER = new B(); 
public static final B SILVER_MEMBER = new B(); 
//각각의 상수를 Class로 설정할경우 코드가 복잡해지고 

//A, B를 비교할때 error를 찾을수있지만 stitch문에 적용할수없다 

//public class

//main

-----------------

//memR.GOLD_MEMBER형태로 불러온다 
//enum class를 사용할경우 관리하기가 간편해지고 switch문에도 적용이된다 

// class memR{ 
// public static final memR PLATINUM_MEMBER = new memR(); 
// public static final memR LOYAL_MEMBER = new memR(); 
// public static final memR GOLD_MEMBER = new memR(); 
// public static final memR SILVER_MEMBER = new memR(); 
// private memR() {} 
// } //enum class를 만들경우 이와같이 상수의 개수만큼

// 생성자가 호출이 되서 객체를 생성한다 

enum memR{ 
PLATINUM_MEMBER,LOYAL_MEMBER,GOLD_MEMBER,SILVER_MEMBER; 

//public class

//main

memR grade = memR.GOLD_MEMBER; 
switch(grade) { 
case PLATINUM_MEMBER: 
System.out.println(30+"% discount"); 
break; 
case LOYAL_MEMBER: 
System.out.println(20+"% discount"); 
break; 
case GOLD_MEMBER: 
System.out.println(10+"% discount"); 
break; 
case SILVER_MEMBER: 
System.out.println(5+"% discount"); 
break; 
} 
------------ 

//enum class안에 멤버나 method를 만들어 효율적으로 사용할수있다

//enum memR
PLATINUM_MEMBER(30),LOYAL_MEMBER(20),GOLD_MEMBER(10),SILVER_MEMBER(5);

//인자를 가진 생성자를 만들어줬기때문에 인자를 입력해주어야한다
int discount;
memR(int discount){
this.discount = discount;
}//생성자생성, 접근제어자로 private, default가 올수있다
public String getDiscount() {
return discount + "% discount";
}//method생성
//할인율이 변경될수 직접바꿔줘야한다는 단점이있지만 switch문보다 성능면에서 더좋다
//public class

//main
memR mm = memR.ROYAL_MEMBER;
System.out.println(mm); //royal member가 출력된다

 

String str = mm.getDiscount(); //값을 return받는 변수생성
System.out.println(str);
//loyal member 20% discount가 출력된다

for(memR marr : memR.values()) { //for each문으로 각각의상수들을 array에 저장한다
System.out.println(marr+marr.getDiscount());
//각각의 상수와 할인율을 출력할수있다

'java' 카테고리의 다른 글

Colletions framework(ArrayList, HashSet)  (0) 2019.08.04
Generic  (0) 2019.08.04
wrapper class  (0) 2019.08.03
Object class(toString(), Equals(), hashCode())  (0) 2019.08.03
예외처리(Exception)  (0) 2019.08.03

wrapper 클래스란 기본형을 객체로 사용하기위해 class로 정의한것을 말한다
더 다양한 기능을 사용하기위해 참조형으로 만든것이다

byte -> Byte

short -> Short

int -> Integer

long -> Long

float -> Float

double -> Double

char -> Character

boolean -> Boolean

 

//public class

//main
int a = 100; //연산하기위해서만 사용
Integer aa = new Integer(100);
Integer aa1 = new Integer("100");

//Integer aa에 100이란 숫자값과 문자값을 넣고 다양하게 사용할수있다 

System.out.println(aa.equals(aa1));
//wrapper class는 equals method를 overriding했기때문에 true값이 나온다 
System.out.println(aa.toString());
//wrapper class는 toString method를 overriding했기때문에 100이란 값이 나온다 

String str = 100;
int ii = Integer.parseInt(str); //Integer.parseInt()는 문자열을 정수형으로 바꿔준다
System.out.println(ii); //100이란 정수 값이 출력된다
int ii2 = ii + 100; //정수형으로 바꿧기때문에 error가 없다
System.out.pintln(ii2);

String str2 = Integer.toBinaryString(200); // toBinary는 숫자값을 문자열(string type)으로 반환해준다
System.out.println(str2); //이진수형태인 문자열로 출력

int ii3 = Integer.parseInt(str2, 2); //str2에 2진수값을 정수로 변환
System.outprintln(ii3); //정수 200이 출력된다

int ii4 = Integer.parseInt("100",8);
System.out.println(ii4); //100이라는 8진수를 10진수로 표현

Integer intg = new Integer(150);
int intg1 = intg.intValue(); 

//intValue method를 통해 Integer 객체를 기본 int형으로 변환한다
int j = intg1 + 100; //정수로 바꿧기때문에 성립이된다

 

//autoBoxing기능으로 자동으로 변환이된다

Integer intg = new Integer(150)
int k = 200;
int j = intg +10;
//Integer 객체를 기본 int형으로 바꾸지않아도

//자동으로 정수형으로 변환이되는걸 anautoBoxing이라고한다
Integer ing = 200; 
Integer ing = new Integer(200);

//아래와같이 autoBoxing처리가 자동으로 된다 

'java' 카테고리의 다른 글

Generic  (0) 2019.08.04
이넘클래스(enum class)  (0) 2019.08.03
Object class(toString(), Equals(), hashCode())  (0) 2019.08.03
예외처리(Exception)  (0) 2019.08.03
다형성(Polymorphism) -second  (0) 2019.08.03

Object class
최상위클래스로 모든클래스는
암시적으로 Object를 상속받고있다
-----
//public class ObjectEx extends Object

//입력하지않아도 암시적으로 extends Object 를 상속하고있다
//main
ObjectEx obj = new ObjectEx();
obj.toStringFunc(obj);
}

//toStringFunc

public void toStringFunc(ObjectEx obj) {
System.out.println(obj); 
//객체명만 들어갈경우 자동으로 toString method를 호출한다
System.out.println(toString()); 
//toString method는 해당class 객체를 문자열로 반환해주는 역할이다
//getClass().getName()+'@'+Integer.toHexString(hashCode())가 출력된다
System.out.println("hi"+this); //this는 해당class obj를 의미한다
} //객체에 문자열 +연산을하는경우 toString()method가 자동으로 호출된다

 
public String toString() {

//toString 은 복잡하게출력되므로 알기쉽게 overriding을해서 사용한다

return "this is ObjectEx class";
}
------

//public class

//main
int aa = 100;
int bb = 100;

 

if(aa==bb) { 
System.out.println("aa와 bb는 서로같다"); 
}else { 
System.out.println("aa와 bb는 서로 다르다"); 
} //== 비교연산자는 기본자료형을 비교하는경우 값을 비교하기때문에

//서로 같다라는 내용이 출력된다


String str1 = new String("heelo");
String str2 = ("heelo");

 

if(str1==str2) { 
System.out.println("str1, str2는 같다"); 
}else { 
System.out.println("str1, str2는 다르다"); 
} //== 비교연산자는 참조형(Reference Type)을 비교할경우

//주소값을 비교하기때문에 서로 다르다라는 내용이 출력된다.

//만약에 str1=str2; 를한다면 주소값이 같아지기때문에 같다가 출력된다. 

 

//equals는 앞의객체와 뒤의객체를 비교해 true, false값을 반환한다
if(str1.equals(str2)) { 
System.out.println("str1, str2는 같다");
}else { 
System.out.println("str1, str2는 다르다");
} //String 객체는 Object class에 있는 equals method를 

//overriding을해서 비교하기때문에 '다르다'가출력된다 

//String 객체의 Equals method는 overriding된 method여서 내용을 비교한다


value va1 = new Value(10);
value va2 = new Value(10); //서로 다른 instance를 가리킨다

if(val1.equals(var2)) {
System.out.println("va1과 va2는 서로같다");
}else { 
System.out.println("va1과 va2는 서로 다르다");
} //Value class는 overriding을 하지 않아서 서로 "다르다"가 출력된다 

//va1 = va2;를 입력할경우 "같다"가 출력된다

//Equals method가 Objet class 에 있는경우 주소값을 비교한다

 

//hashCode는 주소의 값을 반환해주는 method이다

System.out.println(str1.hashCode()); 
System.out.println(str2.hashCode()); //같은 값이 출력된다 
//서로다른주소의 값이 나와야하지만 내용이 같은경우 

//String 객체에서는 hashCode의 값이 같아지도록 overriding을했다  

 

System.out.println(va1.hashCode()); 
System.out.println(va2.hashCode()); //다른값이 출력된다

//class Value
int a;
public Value(int a) {
this.a = a;
}


// public boolean equals(Object obj){
// if(obj != null && obj instanceof Value) {
// return a == ((Value)obj).a;
// }else {
// return false;
// } //내용을 비교할경우 이와같이 overriding을 해줘야 "같다"가 출력된다.
// } //String형태도 이와같이 overriding되서 사용되고있다 

'java' 카테고리의 다른 글

이넘클래스(enum class)  (0) 2019.08.03
wrapper class  (0) 2019.08.03
예외처리(Exception)  (0) 2019.08.03
다형성(Polymorphism) -second  (0) 2019.08.03
다형성(Polymorphism) -first  (0) 2019.08.03

예외처리란 프로그램 실행시 발생할수있는 상황들을 미리 정해놓고

예외가 발생했을경우에 대비하여 코드를 작성하여

프로그램이 정상적으로 작동하게하기위해서다.

 

컴파일 에러는 컴파일할때 발생하는 에러로 문법상의 오류를 말한다

런타임 에러는 컴파일후 실행할때 발생하는 에러이다

런타임 에러는 error와 exceptiond으로 나눌수있는데

error는 코드에서 처리할수없는 심각한오류를말하고

exception은 코드에서 처리할수있는 가벼운 오류를 말한다

 

exception 에는 IOException, ClassNotFoundException, RuntimeException등이 있는데

IOException과 ClassNotFoundException은 사용자의 입력 실수에 의해 오류가 발생하는 경우이다

IOException과 ClassNotFondException경우 컴파일시 예외처리를 해줘야한다

 

RuntimeException에는 ArithmeticException, NullPointerException, IndexOutOfBoundsException

등이 있는데 개발자에의해 오류가 발생하는 경우이다


직접처리
try {
예외발생 예상코드
}cath(해당 예외 클래스 e){
예외처리 코드
}
선언처리
public void aaa() throws IOException{
int i = System.in.read();
//aaa()를 호출하면 IOException class도 같이호출되

//입력시 발생할지도모를 오류를 해결한다 
----------

//public class

//main
int intArray[] = {1,2,3,4,5}; 
//변수를 try 안에서 선언하면 지역변수가되서 사라지게되기때문에 밖에서 선언해줘야한다

try {
System.out.println(intArray[0]);//공간이 하나이므로 1출력
System.out.println(intArray[5]);//공간이 6개이므로 에러
}catch(Exception e) {
    System.out.println("예외발생");

}finally {

    System.out.println("항상 실행되어야될 코드");
} //finally는 반드시 수행되는부분이다 

//return이 있을경우 다음 문장을 수행하지않고 blcok을 빠져나오게되는데 
//finally가 있으면 중간에 return이 있어도 반드시 수행된다 
//주로 DB접속을 끈을때 사용한다 
--------

//public class

//main
int intArray[] = {1,2,0,4,5};

try {
System.out.println(intArray[0]); //첫번째 배열 1이 출력
System.oot.println(intArray[4]/intArray[2]); 

//세번째 배열값 0으로 나눌수없으므로 error발생

System.out.println(intARray[5]); //배열이 6개가 아니므로 error발생

String str = null;  
str.toString(); 

//toString은 문자열을 출력하는 method인데 str은 null값이므로 error발생 

}catch(ArithmeticException e) {
    System.out.pintln(e.getMessage()); 

}catch(ArrayIndexOutOfBoundsException e) {
    System.out.println(e.toString()); 

//발생할수있는 예상 코드가 여러개일경우 다중 catch문을 사용한다

}catch(Exception e) {

//예상치 못한 error를 상위class의 Exception을 입력
//Exception이 상위의 class이므로 가장 마지막에 적어줘야 하위class의 error check가 실행된다.    

    e.printStackTrace(); 

}System.out.println("항상 실행되어야할 코드"); 

//e.getMessage()를하면 에러설명을볼수있다

//e.toString()을 쓰면 자세한 에러설명을해준다

//e.printStackTrace();를 입력할경우 더 자세한 에러설명을 해준다 
-----

//public class

//main
ThrowEx a = new ThrowEx();
a.throwSample(12); //10보다 크므로 error message 를 출력한다

//class ThrowEx
public void throwSample(int n) {

//예외를 발생시켰으므로 try, catch를 이용하여 처리를해야한다
try {  
if(n > 10) { 
throw new Exception("n 값이 10보다 크다");

//throw는 문자를이용해 예외를 발생시키겠다는 의미이다 
}}catch(Exception e) {
     e.printStackTrace();

}
------

//public class

//main

ThrowEx a = new ThrowEx();
try {
a.throwSample(12);
}catch(Exception e) {e.printStackTrace();}

//throws Exeption을 가진 method를

//호출했기때문에 try,catch문으로 처리를해줘야한다

//class ThrowEx
public void throwSample(int n) throws Exception{  
if(n > 10) { 
throw new Exception("n 값이 10보다 크다");
}} //throws Exeption은 예외를 호출한쪽으로 던진다는의미로 
//이 method를 호출할때 예외처리를 해줘야한다는뜻이다
------

//public class

//main

ThrowEx a = new ThrowEx();
try {
a.throwSample(12);
}catch(Exception e) {

e.printStackTrace();

}

//class ThrowEx
public void throwSample(int n) throws IllegalArgumentException,IOException{
//예외발생이 2개일때 여러개의 예외를 호출하는 쪽으로 넘겨줌으로써 처리할수있다 

//try,catch문을 중첩되게 사용해서 IOException을 처리할수도있고

//Exception을 넘겨줄때 IllegalArgumentExeption,IOException을 같이 넘겨줄수도있다

try {
int aa = System.in.read(); //입력받을땐 IOException처리를 해줘야한다
System.out.println(aa); //a를 입력할경우 아스키값 97이출력
}catch(IOException e) {
e.printStackTrace();
}//try,catch문으로 예외처리를 할수있고

//try,catch문 없이 throws로 여러개의 예외를 한번에넘겨줄수있다
if(n > 10) {
throw new IllegalArgumentException("n 값이 10보다 크다");
}}
------

//public class

//main

MyException mye = new MyException(); 

//method에서 예외처리를 하지않았으므로 여기서해줘야한다
try {
mye.IOExc();
}catch(IOException e) {
e.printStackTrack();
//throws나 try,catch문 둘중하나를 입력해 예외처리를 해줘야한다

 

//class MyException
void ArithmeticExc() {
throw new ArithmeticException();
//실행을해봐야 알수있으므로 예외처리를 하지않는다

 

void IOExc() {
throw new IOException();
} //컴파일시 예외처리를 하라고 강요되어진다

 

void IOExe1() {
try {
throw new IOException()
} cath (IOException e){
e.printStackTrace();
} //미리 IOException처리를 해주어야한다
------

//public class

//main

Divide di = new Divide(); 
di.setNumber(5, 0);
try {
di.divide(); //0으로 나누기때문에 error가 생긴다
}catch(MyException e) {
e.printStackTrace();
System.out.println(e.getMessage());
//exception!: can not divide by zero 가 출력된다
//method에서 발생한 예외를 try,catch문을 이용해 처리한다 

//class Divide
int n1, n2;
public void setNumber(int n1, int n2) {
this.n1 = n1;
this.n2 = n2;
}
public void divide() {
if(this.n2 == 0) {
throw new MyException("exception!: can not divide by zero");
} //0일경우 Myexception을 호출해 예외를 발생시켜준다 
System.out.println(this.n1/this.n2);
}


//class MyException extends Exception
public MyException() {
super(); //부모의 기본생성자 호출
//생성자를 만들어준다
public MyException(String msg) {
super(msg);
//생성자를 overriding해준다

'java' 카테고리의 다른 글

wrapper class  (0) 2019.08.03
Object class(toString(), Equals(), hashCode())  (0) 2019.08.03
다형성(Polymorphism) -second  (0) 2019.08.03
다형성(Polymorphism) -first  (0) 2019.08.03
인터페이스(interface)  (0) 2019.08.03

+ Recent posts