조용한 담장

Dart : Collections 본문

Dart

Dart : Collections

iosroid 2019. 11. 19. 19:02

Dart 의 collections 자료형 클래스인 List, Set, Map 을 살펴보자.

List

List<E> class

 

List 는 두가지 타입이 있다.

  • 길이 고정된 리스트 : 리스트의 길이를 변경하는 동작에 에러를 발생시킨다. new List(n), List(n)

  • 길이 증가 가능한 리스트. List(), []

List<int> fixedLengthList = List(5);
// List<int> fixedLengthList = new List(5);
// fixedLengthList.add(6); // error!
print(fixedLengthList); // [null, null, null, null, null]
List<int> growableList1 = List();
// List<int> growableList1 = new List();
print(growableList1.length); // 0
growableList1.add(2);
print(growableList1); // [2]
List<int> growableList2 = [];
growableList2.add(3);
print(growableList2); // [3]
List<int> growableList3 = [1, 2];
growableList3.add(3);
print(growableList3); // [1, 2, 3]

Constructors

List([int length ])

: length 길이의 null 로 채워진 리스트를 생성한다.

List.filled(int length, E fill, { bool growable: false })

: 각 element 가 fill 값을 length 길이의 리스트를 생성한다.

List.from(Iterable elements, { bool growable: true })

: elements 를 가진 리스트를 생성한다. subtype 으로 down-cast 가 가능하다.

List.generate(int length, E generator(int index), { bool growable: true })

: generator 가 생성하는 값을 가진 length 길이의 리스트를 생성한다.

List.of(Iterable<E> elements, { bool growable: true })

: elements 로 부터 리스트를 생성한다. 내부적으로 List.from 을 쓰지만 down-cast 는 불가능하다.

List.unmodifiable(Iterable elements)

: 값을 수정할 수 없는 리스트를 생성한다.

 

var basicConstructor = List();
basicConstructor.add(1);
print(basicConstructor); // [1]
var filledConstructor = List.filled(3, 1);
print(filledConstructor); // [1, 1, 1]
Set<num> setC = {1.0, 2.0, 3.0};
List<double> fromConstructor = List.from(setC); // type cast num to double
print(fromConstructor); // [1.0, 2.0, 3.0]
print(fromConstructor.runtimeType); // List<double>
var generateConstructor = List.generate(5, (index) {
return index*2;
});
print(generateConstructor); // [0, 2, 4, 6, 8]
List<num> ofConstructor = List.of(setC);
// List<double> ofConstructor = List.of(setC); // error
print(ofConstructor); // [1.0, 2.0, 3.0]
print(ofConstructor.runtimeType); // List<num>
final unmodifiableConstructor = List.unmodifiable(setC);
// unmodifiableConstructor[0] = 1; // error
print(unmodifiableConstructor); // [1.0, 2.0, 3.0]

DartPad 는 javascript 로 변환되어 실행해서 소수점에 대한 값이 좀 다르게 나온다.

Operators

+, ==, [], []=

 

var a = [1, 2];
print(a[0]); // 1
a[0] = 3;
print(a[0]); // 3
var b = a;
print(a == b); // true
var c = a + b;
print(c); // [3, 2, 3, 2]
var d = [0, 1] + c;
print(d); // [0, 1, 3, 2, 3, 2]
d += a;
print(d); // [0, 1, 3, 2, 3, 2, 3, 2]

Static methods

castFrom<S, T>(List<S> source)

copyRange<T>(List<T> target, [ int at, List<T> source, [ int start int end ])

writeIterable<T>(List<T> target, int at, Iterable<T> source)

 

var copyRangeMethod = [100, 200, 0, 0];
List.copyRange(copyRangeMethod, 0, [1, 2, 3, 4, 5], 1, 3);
print(copyRangeMethod); // [2, 3, 0, 0]
List.writeIterable(copyRangeMethod, 2, {10, 11});
print(copyRangeMethod); // [2, 3, 10, 11]
List<int> sourceIntList = [1, 2];
print(sourceIntList.runtimeType); // List<int>
List<dynamic> castFromMethod = List.castFrom<int, dynamic>(sourceIntList);
print(castFromMethod); // [1, 2]
print(castFromMethod.runtimeType); // CastList<int, dynamic>
castFromMethod.add(3);
print(castFromMethod); // [1, 2, 3]

Set

Set<E> class

 

element object 가 하나만 존재할 수 있고 동시에 존재할 수 없다.

 

Set<int> a = {1, 2, 1, 2};
print(a); // {1, 2}
List<int> b = [1, 2, 1, 2];
print(b); // [1, 2, 1, 2]

Set 의 기본 구현은 LinkedHashSet 이다.

== operator 에 의해 유일한 element 인지 확인된다.

element 을 접근할 때 순서에 따라 아래처럼 구분된다.

  • A HashSet is unordered, which means that its iteration order is unspecified,

  • LinkedHashSet iterates in the insertion order of its elements, and

  • a sorted set like SplayTreeSet iterates the elements in sorted order.

Constructors

Set()

: 비어있는 LinkedHashSet 를 생성한다.

Set.from(Iterable elements)

: elements 를 가진 LinkedHashSet 를 생성한다. subtype 으로 down-cast 가 가능하다.

Set.identity()

: 비어있는 identity LinkedHashSet 를 생성한다.

Set.of(Iterable<E> elements)

: elements 로 부터 LinkedHashSet 를 생성한다.

 

var basicConstructor = Set();
print(basicConstructor); // {}
print(basicConstructor.runtimeType); // _LinkedHashSet<dynamic>
List<num> numList = [1, 2, 3, 1];
Set<int> fromConstructor = Set.from(numList);
print(fromConstructor); // {1, 2, 3}
print(fromConstructor.runtimeType); // _LinkedHashSet<int>
var identityConstructor = Set.identity();
print(identityConstructor); // {}
print(identityConstructor.runtimeType); // _LinkedIdentityHashSet<dynamic>
var ofConstructor = Set.of([1, 2, 3, 1]);
print(ofConstructor); // {1, 2, 3}
print(ofConstructor.runtimeType); // _LinkedHashSet<int>

Operators

==

 

var a = {1, 2};
print(a.runtimeType); // _LinkedHashSet<int>
var b = a;
print(a == b); // true

Static methods

castFrom<S, T>(Set<S> source, { Set<R> newSet() })

 

Set<int> sourceIntList = {1, 2};
print(sourceIntList.runtimeType); // _LinkedHashSet<int>
Set<num> castFromMethod = Set.castFrom<int, num>(sourceIntList);
print(castFromMethod); // {1, 2}
print(castFromMethod.runtimeType); // CastSet<int, num>

Map

Map<K, V> class

 

element 을 접근할 때 순서에 따라 아래처럼 구분된다.

  • The plain HashMap is unordered (no order is guaranteed),

  • the LinkedHashMap iterates in key insertion order,

  • and a sorted map like SplayTreeMap iterates the keys in sorted order.

Constructors

Map()

: 비어있는 LinkedHashMap 을 만든다.

Map.from(Map other)

: 다른 Map 으로 부터 LinkedHashMap 을 만든다.

Map.fromEntries(Iterable<MapEntry<K, V>> entries)

: Map 을 만들고 모든 MapEntry 를 추가한다.

Map.fromIterable(Iterable iterable, { K key(dynamic element), V value(dynamic element) })

: iterable 로 부터 LinkedHashMap 을 만든다.

Map.fromIterables(Iterable<K> keys, Iterable<V> values)

: keysvalues 로 LinkedHashMap 을 만든다.

Map.identity()

: identity map (기본 LinkedHashMap) 을 만든다.

Map.of(Map<K, V> other)

: other 가 가진 key, value 값들로 LinkedHashMap 을 만든다.

Map.unmodifiable(Map other)

: 값을 수정할 수 없는 Map 을 other 로 부터 만든다.

 

var basicConstructor1 = Map();
print(basicConstructor1); // {}
print(basicConstructor1.runtimeType); // _InternalLinkedHashMap<dynamic, dynamic>
var basicConstructor2 = {};
print(basicConstructor2.runtimeType); // _InternalLinkedHashMap<dynamic, dynamic>
var fromConstructor = Map.from({'a': 1, 'b': 2});
print(fromConstructor); // {a: 1, b: 2}
var fromEntriesConstructor = Map.fromEntries([MapEntry('a', 1), MapEntry('b', 2)]);
print(fromEntriesConstructor); // {a: 1, b: 2}
print(fromEntriesConstructor.runtimeType); // _InternalLinkedHashMap<String, int>
var fromIterableConstructor1 = Map.fromIterable([1, 2, 3],
key: (item) => item.toString(),
value: (item) => item * item);
print(fromIterableConstructor1); // {1: 1, 2: 4, 3: 9}
print(fromIterableConstructor1.runtimeType); // _InternalLinkedHashMap<String, dynamic>
var fromIterableConstructor2 = Map.fromIterable([1, 2, 3]);
print(fromIterableConstructor2); // {1: 1, 2: 2, 3: 3}
print(fromIterableConstructor2.runtimeType); // _InternalLinkedHashMap<dynamic, dynamic>
List<String> letters = ['b', 'c'];
List<String> words = ['bad', 'cat'];
Map<String, String> fromIterablesConstructor = Map.fromIterables(letters, words);
print(fromIterablesConstructor); // {b: bad, c: cat}
print(fromIterablesConstructor.runtimeType); // _InternalLinkedHashMap<String, String>
var identityConstructor = Map.identity();
print(identityConstructor); // {}
print(identityConstructor.runtimeType); // _CompactLinkedIdentityHashMap<dynamic, dynamic>
var ofConstructor = Map.of(fromIterablesConstructor);
print(ofConstructor); // {b: bad, c: cat}
print(ofConstructor.runtimeType); // _InternalLinkedHashMap<String, String>
ofConstructor['b'] = 'good';
print(ofConstructor); // {b: good, c: cat}
var unmodifiableConstructor = Map.unmodifiable(ofConstructor);
print(unmodifiableConstructor); // {b: good, c: cat}
// unmodifiableConstructor['c'] = 'cow'; // error

Operators

[], []=, ==

 

var a = {'a': 1, 'b': 2};
print(a['a']); // 1
a['a'] = 3;
print(a['a']); // 3
var b = a;
print(a == b); // true

Static methods

castFrom<K, V, K2, V2>(Map<K, V> source)

 

Map<String, int> sourceIntList = {'a': 1, 'b': 2};
print(sourceIntList.runtimeType); // _InternalLinkedHashMap<String, int
Map<dynamic, dynamic> castFromMethod = Map.castFrom<String, int, dynamic, dynamic>(sourceIntList);
print(castFromMethod); // {a: 1, b: 2}
print(castFromMethod.runtimeType); // CastMap<String, int, dynamic, dynamic>

Reference

Dart API reference documentation

 

'Dart' 카테고리의 다른 글

Dart : Generators  (0) 2019.11.22
Dart : Generics  (0) 2019.11.22
Dart : print  (0) 2019.11.04
Dart : Asynchronous programming  (0) 2019.10.24
Dart : Class  (0) 2019.10.02
Comments