一个泛型的例题代码,看了有几点疑问,求解答
这个就是定义一个泛型类LinkedList,做一个针对(整型数据和Student类型数据)的链表
Student类型已在开头定义好 ,Node就是针对链表中的节点进行一些操作,LinkedList就是调用Node中的一些方法再加上自己的方法实现链表的功能,一下是代码。
我的问题代码在后面提出。
第一个问题:在LinkedList泛型那段中的一个方法public T this[int index],这段代码如何实现的对LinkedList数组中的每一个元素赋值,求详细分析过程。
第二个问题:在Node类和LinkedList类定义的时候,最后都重载了一个Tostring方法,有什么作用,想用这个来干什么,去掉了又什么影响,为什么。
问题可能不好回答,还是求大神帮忙了
Student类型已在开头定义好 ,Node就是针对链表中的节点进行一些操作,LinkedList就是调用Node中的一些方法再加上自己的方法实现链表的功能,一下是代码。
我的问题代码在后面提出。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace GenericSamp
{
public class Student
{
private string StudentName;
private int StudentAge;
public Student(string name, int age)
{
this.StudentName = name;
this.StudentAge = age;
}
public override string ToString()
{
return this.StudentName + ":年龄" + this.StudentAge + "岁";
}
}
public class Node<T>
{
T data;
Node<T> next;
public Node(T data)
{
this.data=data;
this.next=null;
}
public T Data{
get {return this.data;}
set{data=value;}
}
public Node<T> Next{
get{return this.next;}
set{this.next=value;}
}
public void Append(Node<T> newNode){
if(this.next==null){this.next=newNode;}
else{next.Append(newNode);}
}
public override string ToString(){
string output=data.ToString();
if(next!=null){output+=","+next.ToString();}
return output;
}
}
public class LinkedList<T>
{
Node<T> headNode = null;
public void Add(T data)
{
if (headNode == null)
{
headNode = new Node<T>(data);
}
else
{
headNode.Append(new Node<T>(data));
}
}
public T this[int index]
{
get
{
int temp = 0;
Node<T> node = headNode;
while (node != null && temp <= index)
{
if (temp == index)
{
return node.Data;
}
else
{
node = node.Next;
}
temp++;
}
return default(T);
}
}
public override string ToString()
{
if (this.headNode != null)
{
return this.headNode.ToString;
}
else
{
return string.Empty;
}
}
}
class Program
{
static void Main(string[] args)
{
LinkedList<int> intList=new LinkedList<int>();
for (int i = 0; i < 5; i++)
{
intList.Add(i);
}
Console.WriteLine("整型List的内容为:" + intList);
LinkedList<Student> StudentList = new LinkedList<Student>();
StudentList.Add(new Student("张三",20));
StudentList.Add(new Student("李四",22));
StudentList.Add(new Student("王五",21));
Console.WriteLine("Student类型List的内容为:" + StudentList);
}
}
}第一个问题:在LinkedList泛型那段中的一个方法public T this[int index],这段代码如何实现的对LinkedList数组中的每一个元素赋值,求详细分析过程。
第二个问题:在Node类和LinkedList类定义的时候,最后都重载了一个Tostring方法,有什么作用,想用这个来干什么,去掉了又什么影响,为什么。
问题可能不好回答,还是求大神帮忙了
...全文
相关推荐
C#泛型类、泛型方法、泛型接口、泛型委托的实例
泛型类、泛型方法、泛型接口、泛型委托 泛型类、泛型方法、泛型接口、泛型委托
Java泛型使用
Java泛型使用 1. 泛型 1.1 什么是泛型,为什么引入泛型 在项目中,我们的功能代码往往要考虑之后的复用!!!这要求功能代码尽可能的支持更多类型,在不考虑泛型的情况下,如果需要更换数据类型,只能重新完成对应数据类型的功能代码。有可能出现各式各样的类型,工作是重复的!!! 这里不单单是对于功能模块的要求封装。同时需要对数据类型进行统一的约束!!!根据用户的要求对应数据类型。 Java的泛型就是来解决对应的问题 格式: 泛型可以在方法中使用 泛型可以在类中使用 泛型可以在接口中使用 1.2 泛型可以在方法中使用 使用静态方法举例说明泛型在方法中的使用格式 格式: public
java泛型总结
深入理解java泛型,包括类名泛型的定义,方法泛型定义,泛型的返回
gson解析泛型和将泛型转为json字符串
gson 解析泛型和将泛型转为json字符串
《c++泛型stl原理和应用》全部例题源码
《c++泛型stl原理和应用》全部例题源码哟 全部手工写入并作了一些修改


