Skip to Content
Head First Kotlin程序设计
book

Head First Kotlin程序设计

by Dawn Griffiths, David Griffiths
August 2020
Intermediate to advanced
483 pages
11h 24m
Chinese
China Machine Press
Content preview from Head First Kotlin程序设计
你现在的位置 4 263
集合
List
允许重复项
如你所知,使用
List
或是
MutableList
比使用数组更加灵
活。与数组不同,你可以明确选择集合是否为不可变,或者
其值是否可以被添加、移除、更新。
但是,在某些情况下,使用
List
(或
M
utableList
)并不是
很有效。
想象一下,你正在安排一顿和一群朋友的聚餐,你需要知道
有多少人参加以便预定餐桌。你可以使用
List
来记录,但有个
问题:
List
以有重复项。那么就有可能发生,在创建的朋友
List
中,某些朋友被列出两次:
在本章前面的内容中
我们讨论了
Kotlin
中不同类型的集合
你认
为哪种类型的集合最适合这种情况呢
但是如果想知道有多少个唯一的朋友在
List
中,你
不能简单地使用代码:
val friendList = listOf("Jim",
"Sue",
"Sue",
"Nick",
"Nick")
friendList.size
找出需要为多少人预定餐桌。因为
size
属性只认为
List
中有
5
个元素,它不关心其中的两个是重复的。
在这种情况下,我们需要使用不允许重复值存在的集合。那
么我们应该使用哪种类型的集合呢?
引用
引用
引用
0
1
2
String
“Jim”
String
“Sue”
String
“Nick”
val List<String>
引用
friend
List
引用
引用
3
4
List
的大小为
5
只有
3
个唯一的值
这里有三位朋友
Jim
Su
e
Nick
Su
e
Nick
被列
出两次
动动脑筋
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.

Read now

Unlock full access

More than 5,000 organizations count on O’Reilly

AirBnbBlueOriginElectronic ArtsHomeDepotNasdaqRakutenTata Consultancy Services

QuotationMarkO’Reilly covers everything we've got, with content to help us build a world-class technology community, upgrade the capabilities and competencies of our teams, and improve overall team performance as well as their engagement.
Julian F.
Head of Cybersecurity
QuotationMarkI wanted to learn C and C++, but it didn't click for me until I picked up an O'Reilly book. When I went on the O’Reilly platform, I was astonished to find all the books there, plus live events and sandboxes so you could play around with the technology.
Addison B.
Field Engineer
QuotationMarkI’ve been on the O’Reilly platform for more than eight years. I use a couple of learning platforms, but I'm on O'Reilly more than anybody else. When you're there, you start learning. I'm never disappointed.
Amir M.
Data Platform Tech Lead
QuotationMarkI'm always learning. So when I got on to O'Reilly, I was like a kid in a candy store. There are playlists. There are answers. There's on-demand training. It's worth its weight in gold, in terms of what it allows me to do.
Mark W.
Embedded Software Engineer

You might also like

面向对象的思考过程(原书第5版)

面向对象的思考过程(原书第5版)

马特 魏斯费尔德
GraphQL 学习指南

GraphQL 学习指南

Eve Porcello, Alex Banks
前端架构设计

前端架构设计

Micah Godbolt

Publisher Resources

ISBN: 9787111662358