JAVA

JAVA: Deep and Shallow Copying, String Class Methods

mossybeach 2024. 6. 26. 20:02

Today we learnt the concept of deep and shallow copying

These methods applies to Arrays, primitive and reference types and effect them a little bit differently!

 First lets define what deep and shallow copies are and the pros and cons of using them :3

 

Shallow Copy

in a nutshell, instead of copying the content of a variable, we just copy the address of which it is stored!!

 

so if we type:

int[ ] arr01 = new int[ ]{1,2,3,4,5};

int[ ] arr02 = arr01;

 

we are essentially saying this!

this becomes apparent when we search for their addresses by typing System.out.println(arr01) and they share the same address!!

 

Pros of shallow copying:

  • fast and simple
    Cons of shallow copying: 
  • Since its a copy of the original object itself, we are unable to create an independant new object and apply differences or redefine it without changing the original array

 


Deep Copy

This is where a seperate identity is created with the copy of the original object! It has a completely different address to the original!!

 

Pros of Deep copying:

  • We can alter and create unique objects and it won't effect the original that we copied from

    Cons of shallow copying: 
  • Since we are bringing all the data inside of the object, compared to the shallow copy it will be more complicated and take more time!

 


So cool!! 

 

Now lets see different examples, as well as some methods used for copying arrays.

 

TO NOTE: All copying methods are used to produce shallow copies!!

 

this is how it works for reference types except for String but more on that later!!

 

.arraycopy( )

this can be used like this:

.arraycopy(the array to copy, the starting point of said array, array that will receive copy, the start of the said array, end)

 

int[] arr01 = new int[] {-1,20,30,40,50};

System.arraycopy(arr01, 0, arr03, 5, 5);

System.out.println(Arrays.toString(arr03));

//[0, 0, 0, 0, 0, -1, 20, 30, 40, 50]


.clone()

this can be used for arrays but also for string and class! 

 

int[] arr04 = arr01.clone();

System.out.println(Arrays.toString(arr04)); //[-1, 20, 30, 40, 50]

arr01[0]= 100;

System.out.println(Arrays.toString(arr04)); //[-1, 20, 30, 40, 50]

 


.Arrays.copyOf( )

used with the array to copy and the length in which to copy!

Arrays.copyOf(arr01,4);

 

 


As mentioned before, a wacky thing about copying reference type is that despite using deep copy methods, and having seperate addresses, if we change something from the original object, it will also effect the copy.

This is because we can't copy the contents of the object as they are stored seperately and the copy and the copied share the address!!

 

this diagram is very helpful in explaining!!


BUT THERE IS ONE EXCEPTION WHICH IS STRING!!

the thing about string is that if there is a change in its original value, it will completely delete itself and create and save it's new self in a different part of the memory. BUT!! when its being saved, if there is a same value in the memory, instead of creating a new place, it will just copy the address of the same one!! 

 

public static void main(String[] args) {

String str = "안녕하세요";

String str2 = "안녕하세요";

 

System.out.println(str);

System.out.println(str2);

 

if(str == str2) {

System.out.println("같아요");// 같아요, ==는 동일객체인지 확인할때 (주소)

}

 

str = new String("Hi");

str2 = new String("Hi");

 

if(str == str2) {

System.out.println("같아용");

}else {

System.out.println("달라용"); //달라용 

new를 쓰면 새로운 곳에 변수가 생성되고 값이 저장되기 때문

}

 

if(str.equals(str2)) {

System.out.println("같아요. value"); //같아요, equals는 값자체가 같은지 확인할때!

}}


String Class Methods

We learned some useful string methods to extract certain information in string format :3

 

  • .charAt( index ): we can get the character in place of a certain string, just type the index number

  • toCharArray( ): this method changes a string into an array, super useful!

  • indexOf(“text”): this is similar to charAt but it finds the index of the character you're hoping to find! 
    System.out.println(str01.indexOf("h", str01.indexOf("h")+1));
    the example above is looking for the index of char "h", however if we add the +1, like the second argument here it means it will search for the next h (if there is one!) it will also return a value of -1 if there is no match

  • .replace( ): it will replace the character of your choosing! see below :3
    str01.replace("f", "가")                                                           ; 

  • .substring( ): There are 2 versions, one with cut to size and one that has a start and end

System.out.println(hello); //안녕하세요.

System.out.println(hello.substring(2)); //하세요.

 

  • toUpperCase(), .toLowerCase(): self- explanatory!

  • trim( ): gets rid of blank spaces

String text = "  hello  ";

System.out.println(text.length()); //9

System.out.println(text.trim().length()); //5

 

  • .valueOf( ): changing values to different types, usually followed by String or Integer

int num = 123;

String number = String.valueOf(num); //"123"

System.out.println(number);

num = Integer.valueOf(number); //123

 

.contains( ): checking if something is contained in a value we’re checking : it returns boolean and always use " " 

String email = "poseidon@kakao.com";

if(email.contains("@")) {

System.out.println("이메일입니다");

}else {

System.out.println("이메일이 아닙니다");

}

 


StringBuilder / Buffer

It is something we very briefly touched upon but it is a type of class we can use to edit string!

 

1.) we start by creating a new StringBuilder.

StringBuilder sb = new StringBuilder()                                                                                                                                   ;

we will be using the method of .toString() to print out everything we've typed on our sb!

 

2.) then we use the .append( ) method to add different strings

sb.append("hi"); // 추가

sb.append(" java");

System.out.println(sb.toString()); //hi java

char ch = sb.charAt(2);

System.out.println(ch); //  (space between hi and java)

 

3.) similarly there is .insert( ) where we can insert a string at the char index of our choosing :3

sb.insert(3, "저는 ");

System.out.println(sb.toString()); //hi 저는 java

 

4.) There is also .delete( index, index) where we can delete characters by specifying starting and end index

sb.delete(2, 5);

System.out.println(sb); //hi java

 

5.) .the setCharAt(index, char) method changes a certain character of an index of our choosing!

sb.setCharAt(3, 'J');

System.out.println(sb.toString()); //hi Java

 

6.) finally instead of our go to use of toString() we can use .reverse() which prints the string in reverse (duh!)

System.out.println(sb.reverse()); //avaJ ih