排序和比较:IComparable和IComparer,自己写泛型数组,索引器,

一、比较和排序

1、自己的写的类如果要实现sort方法,就必须实现IComparable里的CompareTo()方法

2、或者自己写一个IComparer的Compare比较器

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;

public class MyIComparable : MonoBehaviour {

    List<StudentI> list = new List<StudentI>();
	void Start () {
        list.Add(new StudentI(10, "张三"));
        list.Add(new StudentI(20, "李思"));
        list.Add(new StudentI(15, "王五"));
        //如果StudentI没有实现IComparable,是不能用sort方法排序的
        list.Sort();
        printList(list);
	}
    //因为所有的list数组都继承ICollection,所有用它做参数,可以传入任何一个泛型数组
    public void printList(ICollection list)
    {
        //用object可以接收任何数据
        foreach (object c in list)
        {
            //如果StudentI没有重写ToString()方法,因为c里面还有年龄,姓名两个元素,还需要遍历c
            print(c);
        }
    }
	
	// Update is called once per frame
	void Update () {
		
	}
}
public class StudentI:IComparable
{
    int age;
    string name;
    public StudentI(int age,string name)
    {
        this.age = age;
        this.name = name;
    }
    //实现IComparable的CompareTo方法,让StudentI类以age来做排序
    public int CompareTo(object obj)
    {
        StudentI s = obj as StudentI;
        if (this.age > s.age)
        {
            return 1;
        }
        else if (this.age == s.age)
        {
            return 0;
        }
        else return -1;
    }
    //重写ToString,这样在做数组遍历时,可以直接输出StudentI的实例,而不用再去遍历StudentI
    public override string ToString()
    {
        return "年龄" + this.age + "名字" + this.name;
    }

}

二、自己写一个泛型数组,实现list的所有功能

using System;

public class MyArrayList<T>
{
    T[] arr;
    T[] arrT;
    //存储数组下标
    int count=0;
    //存储数组容量
    int copacity = 0;
    
    //构造函数初始化数组容量
    public MyArrayList()
    {
        arr = new T[copacity];
    }
    //定义索引器
    public T this[int index]
    {
        get { return arr[index]; }
        set { arr[index] = value; }
    }
    //向数组添加元素
    public void Add(T parameter)
    {
        if (count >= copacity)
        {
            if (copacity == 0)
            {
                copacity = 4;
                arr = new T[copacity];
            }
            else
            {
                copacity *= 2;
                arrT = new T[count];
                arrT = arr;
                arr = new T[copacity];
                //arr = arrT;
                for (int i = 0; i < count; i++)
                {
                    arr[i] = arrT[i];
                }
            }
        }
        arr[count] = parameter;
        count++;
    }
    //在指定索引处插入对象
    //public void Insert(int index, T name)
    //{
    //    bool judge = false;
    //    bool judgeT = true;
    //    if (index < 0 || index > count)
    //    {
    //        throw new Exception("要插入的下标不在服务区");
    //    }
    //    else
    //    {
    //        T[] arrT = new T[count];
    //        if (count == copacity)
    //        {
    //            copacity *= 2;
    //            for (int i = 0; i < count; i++)
    //            {
    //                arrT[i] = arr[i];
    //            }
    //            arr = new T[copacity];
    //            for (int i = 0; i < count; i++)
    //            {
    //                arr[i] = arrT[i];
    //            }
    //        }
    //        for (int i = 0; i < count; i++)
    //        {
    //            arrT[i] = arr[i];
    //        }

    //        for (int i = 0; i <= count; i++)
    //        {
    //            if (i == index)
    //            {
    //                arr[i] = name;
    //                judgeT = false;
    //            }
    //            if (judgeT)
    //            {
    //                arr[i] = arrT[i];
    //            }
    //            if (i == index + 1)
    //            {
    //                judge = true;
    //            }
    //            if (judge)
    //            {
    //                arr[i] = arrT[i-1];
    //            }
    //        }
    //    }
    //    count++;
    //}
    //在指定索引处插入对象
    public void Insert(int index, T name)
    {
        if (index < 0 || index > count)
        {
            throw new Exception("要插入的下标不在服务区");
        }
        else
        {
            T[] arrT = new T[count];
            for (int i = 0; i < count; i++)
            {
                arrT[i] = arr[i];
            }
            //扩充容量
            if (count == copacity)
            {
                copacity *= 2;
                
                arr = new T[copacity];
                for (int i = 0; i < count; i++)
                {
                    arr[i] = arrT[i];
                }
            }
            //倒序从后往前赋值,当复制到指定位置时即可
            for (int ia = count; ia > 0; ia--)
            {
                arr[ia] = arrT[ia - 1];
                if (ia == index)
                {
                    arr[ia] = name;
                    break;
                }
            }
        }
        count++;
    }

    //获取数组的容量
    public int Copacity
    {
        get { return this.copacity; }
    }
    //获取数组有多少个元素
    public int Count
    {
        get { return this.count; }
    }
    //清除所有元素
    public void Clear()
    {
        for (int i = 0; i < count; i++)
        {
            arr[i] = default(T);
        }
    }
    //确定某元素是否在数组中
    public bool Contains(T name)
    {
        for (int i = 0; i < count; i++)
        {
            if (arr[i].Equals(name))
            {
                return true;
            }
        }
        return false;
    }
    //使用二分查找,使用默认的比较器在整个已排序的 List<T> 中搜索元素,并返回该元素从零开始的索引
    public int BinarySearch(T name)
    {
        if (Contains(name))
        {
            return BinarySearchT(0, count - 1, name);
        }
        else
        {
            throw new Exception("要查找的数不在服务区");
        }
    }
    //二分查找
    private int BinarySearchT(int min, int max, T number)
    {
        int middle = (min + max) / 2;
        IComparable middleNumber = arr[middle] as IComparable;
        IComparable searchNumber = number as IComparable;
        if (middleNumber.CompareTo(searchNumber) == 0)
        {
            return middle;
        }
        else if (middleNumber.CompareTo(searchNumber) > 0)
        {
            return BinarySearchT(min, middle, number);
        }
        else
        {
            return BinarySearchT(middle, max, number);
        }
    }
    
    //返回指定值在数组中的位置索引
    public int IndexOf(T name)
    {
        for (int i = 0; i < count; i++)
        {
            if (arr[i].Equals(name))
            {
                return i;
            }
        }
        throw new Exception("元素不在数组中");
    }
    //返回指定值在数组中的最后一个位置索引
    public int LastIndexOf(T name)
    {
        bool judge = false;
        int last = 0;
        for (int i = 0; i < count; i++)
        {
            if (arr[i].Equals(name))
            {
                last = i;
                judge = true;
            }
        }
        if (judge)
        {
            return last;
        }
        throw new Exception("元素不在数组中");
    }

    //移除特定对象
    public void Remove(T name)
    {
        try
        {
            int index = IndexOf(name);
            for (int i = index; i < count-1; i++)
            {
                arr[i] = arr[i + 1];
                arr[i + 1] = default(T);
            }
            count--;
        }
        catch (Exception e)
        {
            throw e;
        }
    }
    //移除指定索引处的对象
    public void RemoveAt(int index)
    {
        bool judge=false;
        try
        {
            for (int i = index; i < count - 1; i++)
            {
                arr[i] = arr[i + 1];
                arr[i + 1] = default(T);
                judge = true;
            }
            if (judge)
            {
                count--;
                judge = false;
            }
        }
        catch(Exception e)
        {
            throw new Exception("有错误:" + e);
        }
    }
    //排序,就是先写一个整数数组的排序方法,然后替换成泛型,再加上IComparable
    public void Sort()
    {
        //int[] arrInt=new int[5];
        
        int subscript = 0;
        for (int i = 0; i < count; i++)
        {
            subscript = i;
            for (int j = i + 1; j < count; j++)
            {
                //要进行排序,参与排序的对象必须实现IComparable才能排序
                if (arr[subscript] is IComparable && arr[j] is IComparable)
                {
                    IComparable a = arr[subscript] as IComparable;
                    IComparable b = arr[j] as IComparable;
                    if (a.CompareTo(b)>0)
                    {
                        subscript = j;
                    }
                }
                else
                {
                    throw new Exception("要参加排比的对象不是IComparable,不能参加选举");
                }
            }
            T temp = arr[i];
            arr[i] = arr[subscript];
            arr[subscript] = temp;
        }
    }
    //将整个数组元素进行反转
    public void Reverse()
    {
        T[] reverseArr = new T[count];
        for (int i = 0; i < count; i++)
        {
            reverseArr[i] = arr[i];
        }
        //reverseArr = arr;不能用这种方法,因为arr为list数组,后面有null,容量大于数量
        for (int i = 0; i < count; i++)
        {
            arr[i] = reverseArr[count - i - 1];
        }
    }
}



  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值