Java:Java面试问题的澄清
我最近参加了 Java 面试问题,并有以下我不知道答案的问题
1>我的班级
class CricketTeam{
String name; //this is the complete name(inclusive of first and last name)
}
板球运动员姓名如下:
1>萨钦·坦杜卡
<代码>2>高塔姆·甘比尔</code>
<代码>3>瑞奇·庞廷
<代码>4>沙希德·阿夫里迪
<代码>5>凯文·彼得森
<代码>6> MS Dhoni
我想按仅姓氏
对上述板球运动员姓名进行排序。提供的Suugestions/代码将不胜感激。
2>使用增强型 for 循环
的优点是什么 java 中的迭代器。在 java 中使用增强的 for 循环有什么优点?当迭代器可以完成这项工作时,为什么首先在 java 中引入它?
I recently attended the Java Interview Questions and had the below queries for which i dont know the answers
1> I have below class
class CricketTeam{
String name; //this is the complete name(inclusive of first and last name)
}
Cricket Players name are as below:
1> Sachin Tendulkar
2> Gautam Gambhir
3> Ricky Ponting
4> Shahid Afridi
5> Kevin Pieterson
6> MS Dhoni
I want to sort the above Cricket Players name by their last name only
.Suugestions/code provided would be appreciated.
2> what are the advantages of using enhanced for loop
againstiterator
in java.what are the advantages of using enhanced for loop in java and why was it introduced in java at the first place when the iterator
could do the job.?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
实现一个
Comparator
,它解析球员姓名中的姓氏并进行比较,然后使用该比较器对板球运动员的集合进行排序。一个简单的示例(没有错误处理,并假设所有玩家只有一个名字,没有中间名):
它更干净,更简洁,更安全(例如,当迭代器意外出现时,避免多个嵌入循环中的特定微妙错误通过调用
next()
次数过多而增加太多)。代码示例(来自 Effective Java 第二版,第 46 项:更喜欢-每个循环到传统的 for 循环):
implement a
Comparator
which parses the last name out of player names and compares these, then sort the collection of cricket players using that comparator.A simplistic example (without error handling, and assuming all players have exactly one first name and no middle name):
it is cleaner, more concise and safer (e.g. avoids specific subtle bugs in multiple embedded loops, when the iterator is accidentally incremented too often by calling
next()
too many times).Code sample (from Effective Java 2nd Edition, Item 46: Prefer for-each loops to traditional for loops):
1.检查此示例代码:
2.它更具可读性,更易于使用并隐藏了不必要的细节。
1.Check this sample code:
2.It is more readable, easier to use and hides unnecessary details.
对于问题1,能否根据_(空格)分隔符拆分
name
字符串,然后根据name_arr[1]
数组元素进行排序? “重新组合”数组元素以进行报告。这是使用简单数组的代码示例。由于要求是根据姓氏进行排序,因此根据空格分隔符分割字符串,翻转结果名称,对数组进行排序,然后通过“重新翻转”进行重组(困惑,但是?:)
对于问题2 ,可读性是我个人的喜好......
For question 1, can you split the
name
string based on the _ (space) delimiter and then sort based on thename_arr[1]
array element? "Regroup" the array elements for reporting.Here's a code example using a simple array. Since the requirement is to sort based on the last name, this splits the string based on the space delimiter, flips the resulting name, sorts the array, and then reforms by "re-flipping" (confused, yet? :)
For question 2, readability is my personal preference...