首页 文章 精选 留言 我的

精选列表

搜索[Rust编程],共10000篇文章
优秀的个人博客,低调大师

(4)剑指Offer之链表相关编程题

一 链表中倒数第k个节点 题目描述: 输入一个链表,输出该链表中倒数第k个结点 问题分析: 一句话概括:两个指针一个指针p1先开始跑,指针p1跑到k-1个节点后,另一个节点p2开始跑,当p1跑到最后时,p2所指的指针就是倒数第k个节点。 思想的简单理解:前提假设:链表的结点个数(长度)为n。规律一:要找到倒数第k个结点,需要向前走多少步呢?比如倒数第一个结点,需要走n步,那倒数第二个结点呢?很明显是向前走了n-1步,所以可以找到规律是找到倒数第k个结点,需要向前走n-k+1步。算法开始: 设两个都指向head的指针p1和p2,当p1走了k-1步的时候,停下来。p2之前一直不动。 p1的下一步是走第k步,这个时候,p2开始一起动了。至于为什么p2这个时候动呢?看下面的分析。 当p1走到链表的尾部时,即p1走了n步。由于我们知道p2是在p1走了k-1步才开始动的,也就是说p1和p2永远差k-1步。所以当p1走了n步时,p2走的应该是在n-(k-1)步。即p2走了n-k+1步,此时巧妙的是p2正好指向的是规律一的倒数第k个结点处。这样是不是很好理解了呢? 考察内容: 链表+代码的鲁棒性 示例代码: /* //链表类 public class ListNode { int val; ListNode next = null; ListNode(int val) { this.val = val; } }*/ //时间复杂度O(n),一次遍历即可 public class Solution { public ListNode FindKthToTail(ListNode head,int k) { ListNode pre=null,p=null; //两个指针都指向头结点 p=head; pre=head; //记录k值 int a=k; //记录节点的个数 int count=0; //p指针先跑,并且记录节点数,当p指针跑了k-1个节点后,pre指针开始跑, //当p指针跑到最后时,pre所指指针就是倒数第k个节点 while(p!=null){ p=p.next; count++; if(k<1){ pre=pre.next; } k--; } //如果节点个数小于所求的倒数第k个节点,则返回空 if(count<a) return null; return pre; } } 二 反转链表 题目描述: 输入一个链表,反转链表后,输出链表的所有元素。 问题分析: 链表的很常规的一道题,这一道题思路不算难,但自己实现起来真的可能会感觉无从下手,我是参考了别人的代码。思路就是我们根据链表的特点,前一个节点指向下一个节点的特点,把后面的节点移到前面来。就比如下图:我们把1节点和2节点互换位置,然后再将3节点指向2节点,4节点指向3节点,这样以来下面的链表就被反转了。 考察内容: 链表+代码的鲁棒性 示例代码: /* public class ListNode { int val; ListNode next = null; ListNode(int val) { this.val = val; } }*/ public class Solution { public ListNode ReverseList(ListNode head) { ListNode next = null; ListNode pre = null; while (head != null) { //保存要反转到头来的那个节点 next = head.next; //要反转的那个节点指向已经反转的上一个节点 head.next = pre; //上一个已经反转到头部的节点 pre = head; //一直向链表尾走 head = next; } return pre; } } 三 合并两个排序的链表 题目描述: 输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。 问题分析: 我们可以这样分析: 假设我们有两个链表 A,B; A的头节点A1的值与B的头结点B1的值比较,假设A1小,则A1为头节点; A2再和B1比较,假设B1小,则,A1指向B1; A2再和B2比较。。。。。。。就这样循环往复就行了,应该还算好理解。 考察内容: 链表+代码的鲁棒性 示例代码: 非递归版本: /* public class ListNode { int val; ListNode next = null; ListNode(int val) { this.val = val; } }*/ public class Solution { public ListNode Merge(ListNode list1,ListNode list2) { //list1为空,直接返回list2 if(list1 == null){ return list2; } //list2为空,直接返回list1 if(list2 == null){ return list1; } ListNode mergeHead = null; ListNode current = null; //当list1和list2不为空时 while(list1!=null && list2!=null){ //取较小值作头结点 if(list1.val <= list2.val){ if(mergeHead == null){ mergeHead = current = list1; }else{ current.next = list1; //current节点保存list1节点的值因为下一次还要用 current = list1; } //list1指向下一个节点 list1 = list1.next; }else{ if(mergeHead == null){ mergeHead = current = list2; }else{ current.next = list2; //current节点保存list2节点的值因为下一次还要用 current = list2; } //list2指向下一个节点 list2 = list2.next; } } if(list1 == null){ current.next = list2; }else{ current.next = list1; } return mergeHead; } } 递归版本: public ListNode Merge(ListNode list1,ListNode list2) { if(list1 == null){ return list2; } if(list2 == null){ return list1; } if(list1.val <= list2.val){ list1.next = Merge(list1.next, list2); return list1; }else{ list2.next = Merge(list1, list2.next); return list2; } }

优秀的个人博客,低调大师

python函数式编程之yield表达式形式

先来看一个例子 def foo(): print("starting...") while True: res = yield print("res:",res) g = foo() next(g) 在上面的例子里,因为foo函数中有yield关键字,所以foo()函数的执行结果g是一个生成器,此时可以使用next(g)或者g.__next__()方法触发生成器的执行 程序的执行结果为 starting... 使用next(g)触发生成器的执行时,程序会按照正常的顺序从上向下执行,遇到yield,程序就会暂停 并把yield后面所接的值返回 打印next(g)的执行结果 def foo(): print("starting...") while True: res = yield print("res:",res) g = foo() print(next(g)) 程序执行结果 starting... None 在上面的例子里,执行一次next(g)方法,程序暂停在yield那一行,此时再次调用next(g),程序会从yield语句那一行继续向下运行 修改上面的代码,多调用几次next方法,并打印next方法的返回结果 def foo(): print("starting...") while True: res = yield print("res:",res) g = foo() print(next(g)) print("*"*20) print(next(g)) 上面这段代码的执行结果为 starting... None ******************** res: None None 可以看到,程序确实按猜想的步骤运行,但是上面的程序也有一个很明显的缺点:那就是上面的代码没有任何的实际意义:res的值永远为None 在实际的开发中,使用yield表达式形式的目的是yield可以得到一个值,然后yield把这个值赋值给某个变量,这样才有实际意义 那应该怎么操作才能为res变量赋一个值呢??那就是调用生成器自身的send方法 send方法可以触发一次生成器执行,同时还可以把send方法的参数传递给yield 修改上面的代码 def foo(): print("starting...") while True: res = yield print("res:",res) g = foo() next(g) print(g.send(5)) 程序的执行结果为: starting... res: 5 None 来分析一下上面的代码的执行过程 : 1.程序开始执行以后,因为foo函数中有yield关键字,所以foo函数并不会真的执行,而是先得到一个生成器g. 2.直到调用next方法,foo函数正式开始执行,先执行foo函数中的print方法,然后进入while循环 3.程序遇到yield关键字,程序暂停,此时next(g)语句执行完成 4.程序执行g.send(5),程序会从yield关键字那一行继续向下运行,send会把5这个值传递给yield 5.yield接收到send方法传递过来的值,然后由yield赋值给res变量 6.由于send方法中包含next()方法,所以程序会继续向下运行执行print方法,然后再次进入while循环 7.程序执行再次遇到yield关键字,yield会返回后面的值,由于yield后面没有接任何参数,所以yield会返回None,程序再次暂停,直到再次调用next方法或send方法 修改代码,多次调用send方法 def foo(): print("starting...") while True: res = yield print("res:",res) g = foo() next(g) print(g.send(5)) print("*"*20) print(g.send(10)) print("#"*20) print(g.send(15)) 执行程序,得到如下结果 starting... res: 5 None ******************** res: 10 None #################### res: 15 None 可以看到,上面代码的执行过程如同上面的分析的执行过程一样运行 在上面的例子里,如果调用send方法时,传递的参数为None,得到的结果会是怎么样的呢?? 从上面的分析中,可以知道: 如果`g.send()`方法发送给yield关键字的参数为None,则yield关键字传递给res变量的值就为None 由于yield后面本来没有接任何值,所以yield返回的值默认也为None,所以程序执行结果会得到两个None 修改代码,验证上面的猜想 def foo(): print("starting...") while True: res = yield print("res:",res) g = foo() next(g) print("#"*20) print(g.send(None)) 查看程序的执行结果 starting... #################### res: None None 从程序的执行结果可以看出,如果调用生成器的send方法时,传递的参数为None,则程序执行的结果将会是两个None 使用yield表达式形式实现linux系统中的"grep -rl root /etc"命令 代码如下: import os def init(func): def wrapper(*args, **kwargs): g = func(*args, **kwargs) next(g) return g return wrapper @init def get_file_path(target): """ get file abspath # 阶段一:递归找文件的绝对路径,把文件的完事路径发送给阶段二 :param target: :return: """ while True: start_path = yield g = os.walk(start_path) for parent_dir, _, files in g: for file in files: file_path = r"%s\%s" % (parent_dir, file) target.send(file_path) @init def opener(target): """ get file obj # 阶段二:收到文件的完整路径,打开文件获取文件对象,把文件对象发送给阶段三 :param target: :return: """ while True: file_path = yield with open(file_path, encoding='utf-8') as f: target.send((file_path, f)) @init def cat_file(target): """ read file content # 阶段三:收到文件对象,for循环读取文件的每一行内容,把每一行内容发给阶段四 :param target: :return: """ while True: file_path, f = yield for line in f: file_content = target.send((file_path, line)) if file_content: break @init def grep(target, pattern): """ grep function # 阶段四:收到文件的一行内容,判断要查找的内容是否在这一行中,如果在,则把文件名发送给阶段五 :param target: :param pattern: :return: """ tag = False while True: file_path, line = yield tag tag = False if pattern in line: target.send(file_path) tag = True @init def printer(): """ print file name # 阶段五:收到文件名,打印结果 :return: """ while True: filename = yield print(filename) path1 = "/root" # 定义要搜索的路径 path2 = "/etc" # 定义要搜索的路径 g = get_file_path(opener(cat_file(grep(printer(), "root")))) print(g) g.send(path1) g.send(path2)

优秀的个人博客,低调大师

Java并发编程 -- 单例模式线程安全问题

单例模式是指对一个对象进行一次实例化,然后全局都可以调用该实例化对象来完成项目的开发。 在计算机系统中,线程池、缓存、日志对象、对话框、打印机、显卡的驱动程序对象常被设计成单例。这些应用都或多或少具有资源管理器的功能。每台计算机可以有若干个打印机,但只能有一个Printer Spooler,以避免两个打印作业同时输出到打印机中。每台计算机可以有若干通信端口,系统应当集中管理这些通信端口,以避免一个通信端口同时被两个请求同时调用。总之,选择单例模式就是为了避免不一致状态,避免政出多头。 实现单例的不同方式 饿汉式单例 饿汉式单例是指在方法调用前,实例就已经创建好了。下面是实现代码: package com.thread.singleton; /** * 单例模式-- 饿汉式 * Created by Fant.J. * 2018/2/25 19:24 */ public class Singleton1 { /** 私有化构造方法,在外部不能实例化对象 */ private Singleton1(){} /** 在这里实例化 静态对象 (优点:不存在线程安全问题。 缺点:每次调用都实例化,占用空间) */ private static Singleton1 singleton1 = new Singleton1(); public static Singleton1 getInstance(){ return singleton1; } } 优点:不存在线程安全问题。 缺点:每次调用都实例化,占用空间 懒汉式单例 懒汉式单例是指在方法调用获取实例时才创建实例,因为相对饿汉式显得“不急迫”,所以被叫做“懒汉模式”。下面是实现代码: package com.thread.singleton; /** * 单例模式 -- 懒汉式 * Created by Fant.J. * 2018/2/25 19:30 */ public class Singleton2 { private Singleton2(){} private static Singleton2 instance; public synchronized static Singleton2 getInstance() { /* 下面这段代码 不是原子性操作 会出现线程安全问题 。**/ if (instance == null) { instance = new Singleton2(); } return instance; } } 在这段代码中,在if语句里面,就可能跑有多个线程同步判断和同步new。会产生线程安全问题。 解决方法: 给方法加上synchronized(变成单线程,影响性能) 给代码块加synchronized(双重检查加锁) 虽然2方法解决了性能问题, 但是还会有问题 。 问题来自 jvm 的优化:指令重排序(有兴趣了解) 我们可以在对象中添加volatile 关键字来 不让jvm对该 对象做优化 完善后的代码如下: package com.thread.singleton; /** * 单例模式 -- 懒汉式 * Created by Fant.J. * 2018/2/25 19:30 */ public class Singleton2 { private Singleton2(){} private static Singleton2 instance; public synchronized static Singleton2 getInstance() { /* 下面这段代码 不是原子性操作 会出现线程安全问题 。 解决方法:1.给方法加上synchronized(变成单线程,影响性能) 2.给代码块加synchronized(双重检查加锁) 虽然2方法解决了性能问题, 但是还会有问题 。 问题来自 jvm 的优化:指令重排序(有兴趣了解) 我们可以在对象中添加volatile 关键字来 不让jvm对该 对象做优化 **/ if (instance == null) { synchronized (Singleton2.class){ if (instance == null){ instance = new Singleton2(); } } } return instance; } }

优秀的个人博客,低调大师

Java并发编程实战系列7之取消与关闭

JAVA媒体提供任务机制来安全的终止线程。但是它提供了中断(interruption),这是一种写作机制,能够使一个线程终止另外一个线程。 一般来说没人希望立即终止,因为必要时总要先清理再终止。 开发一个应用能够妥善处理失败、关闭、取消等过程非常重要也有挑战。 7.1 任务取消 一定不要使用Thread.stop和suspend这些机制。 一种协作机制就是“标记位”。例如使用volatile类型的field来保存取消状态。 @ThreadSafe public class PrimeGenerator implements Runnable { private static ExecutorService exec = Executors.newCachedThreadPool(); @GuardedBy("this") private final List<BigInteger> primes = new ArrayList<BigInteger>(); private volatile boolean cancelled; public void run() { BigInteger p = BigInteger.ONE; while (!cancelled) { p = p.nextProbablePrime(); synchronized (this) { primes.add(p); } } } public void cancel() { cancelled = true; } public synchronized List<BigInteger> get() { return new ArrayList<BigInteger>(primes); } static List<BigInteger> aSecondOfPrimes() throws InterruptedException { PrimeGenerator generator = new PrimeGenerator(); exec.execute(generator); try { SECONDS.sleep(1); } finally { generator.cancel(); } return generator.get(); } } 1.1 中断 下面的例子会出现死锁,线程根本不会停止 class BrokenPrimeProducer extends Thread { private final BlockingQueue<BigInteger> queue; private volatile boolean cancelled = false; BrokenPrimeProducer(BlockingQueue<BigInteger> queue) { this.queue = queue; } public void run() { try { BigInteger p = BigInteger.ONE; while (!cancelled) queue.put(p = p.nextProbablePrime()); } catch (InterruptedException consumed) { } } public void cancel() { cancelled = true; } } interrupt 方法:中断目标线程。isInterrupted:返回目标线程的中断状态。静态的 interrupted方法:清除当前线程的中断状态,并返回它之前的值。大多数可中断的阻塞方法会在入口处检查中断状态 对中断操作(调用interrupt)的正确理解 他并不会真正的中断一个正在运行的线程,而只是发出中断请求,然后由线程在下一个合适的时候中断自己。比如,wait、sleep、 join等方法,当他们收到中断请求或开始执行时,发现某个已经被设置好的中断状态,则抛出异常interruptedException。 每个线程都有一个boolean类型的中断状态。当调用Thread.interrupt方法时,该值被设置为true,Thread.interruptted可以恢复中断。 阻塞库方法,例如sleep和wait、join都会检查中断,并且发现中断则提前返回,他们会清楚中断状态,并抛出InterruptedException。 但是对于其他方法interrupt仅仅是传递了中断的请求消息,并不会使线程中断,需要由线程在下一个合适的时刻中断自己。 通常,用中断是取消的最合理的实现方式。 上面的例子的改进方法就是 public class PrimeProducer extends Thread { private final BlockingQueue<BigInteger> queue; PrimeProducer(BlockingQueue<BigInteger> queue) { this.queue = queue; } public void run() { try { BigInteger p = BigInteger.ONE; while (!Thread.currentThread().isInterrupted()) queue.put(p = p.nextProbablePrime()); } catch (InterruptedException consumed) { /* Allow thread to exit */ } } public void cancel() { interrupt(); } } 7.1.2 中断策略 发生了中断,需要尽快退出执行流程,并把中断信息传递给调用者,从而使调用栈中的上层代码可以采取进一步的操作。当然任务也可以不需要放弃所有操作,可以推迟处理中断清楚,知道某个时机。 7.1.3 响应中断 传递异常 回复中断状态 public class NoncancelableTask { public Task getNextTask(BlockingQueue<Task> queue) { boolean interrupted = false; try { while (true) { try { return queue.take(); } catch (InterruptedException e) { interrupted = true; // fall through and retry } } } finally { if (interrupted) Thread.currentThread().interrupt(); } } interface Task { } } 7.1.6 处理不可中断的阻塞 例如Socket I/O或者内置锁都不能响应中断,这时候该如何做才能终止他们呢?可以通过重写Thread.interrupt方法,例如加入close的逻辑。 7.2 停止基于线程的服务 7.2.1 示例:日志服务 7.2.2 关闭ExecutorService 7.2.3 Poison Pill 例如CloseEvent机制或者POISON对象,来做特殊的识别,从而让程序自己处理停止操作,退出线程。 7.3 处理非正常的线程终止 7.4 JVM关闭 第8章 线程池的使用 一个很好的ThreadPoolExecutor源码分析文档 ThreadPoolExecutor UML图: image image image

优秀的个人博客,低调大师

Java编程思想学习录(连载之:内部类)

用thinkpad打字确实很爽啊! 内部类基本概念 可将一个类的定义置于另一个类定义的内部 内部类允许将逻辑相关的类组织在一起,并控制位于内部的类的可见性 甚至可将内部类定义于一个方法或者任意作用域内! 当然,内部类 ≠ 组合 内部类拥有其外围类 所有元素的 访问权 更有甚,嵌套多层的内部类能透明地访问所有它所嵌入的外围类的所有成员 一个典型的例子:利用 Java内部类 实现的 迭代器模式 // 接口 ------------------------------------------------------------- public interface Selector { boolean end(); Object current(); void next(); } // 外部类(集合类) + 内部类(迭代器类) ------------------------------------------------------------- public class Sequence { // 外部类(代表一个集合类) private Object[] items; private int next = 0; public Sequence( int size ) { items = new Object[size]; } public void add( Object x ) { if( next < items.length ) items[next++] = x; } // 迭代器类:实现了 Selector接口的 内部类 private class SequenceSelector implements Selector { private int i = 0; public boolean end() { return i == items.length; } public Object current() { return items[i]; } public void next() { if( i<items.length ) ++i; } } public Selector selector() { // 该函数也表明了:内部类也可以向上转型,这样在外部就隐藏了实现细节! return new SequenceSelector(); } public static void main( String[] args ) { Sequence sequence = new Sequence(10); for( int i=0; i<10; ++i ) { // 装填元素 sequence.add( Integer.toString(i) ); } Selector selector = sequence.selector(); // 获取iterator! while( !selector.end() ) { print( selector.current() + " " ); selector.next(); } } } // 输出 ------------------------------------------------------------- 0 1 2 3 4 5 6 7 8 9 .this 与 .new 的使用场景 .this用于在内部类中生成对其外部类对象的引用之时,举例: public class DotThis { void f() { print("DotThis.f()"); } public class Inner { // 内部类 public DotThis outer() { // 返回外部类对象的引用 return DotThis.this; // 若直接返回this,那指的便是内部类自身 } } public Inner inner() { return new Inner(); } public static void main( String[] args ) { DotThis dt = new DotThis(); DotThis.Inner dti = dt.inner(); dti.outer().f(); // 输出 DotThis.f() } } .new用于直接创建内部类的对象之时,距离: public class DotNew { public class Inner { } // 空内部类 public static void main( String[] args ) { DotNew dn = new DotNew(); DotNew.Inner dni = dn.new Inner(); //注意此处必须使用外部类的对象,而不能直接 DotNew.Inner dni = new DotNew.Inner() } } 嵌套类(static类型的内部类) 嵌套类是无需依赖其外部类的对象的。非static内部类通过一个特殊的this链接到其外围类的对象,而static类型的内部类无此this引用。 接口与内部类有着很有趣的关系:放到接口中的任何类自动都是public且static,即接口中的任何类都是嵌套类,我们甚至可以在接口的内部类中去实现其外围接口,举例: public interface ClassInInterface { void howdy(); class Test implements ClassInInterface { // 类Test默认static,所以是嵌套类 public void howdy() { print("Howdy!"); } public static void main( String[] args ) { new Test().howdy(); } } } 在 方法 和 作用域 内的内部类 可以称这类为 局部内部类! 方法中定义的内部类只能在方法内被使用,方法之外不可访问,举例: public class Parcel { // parcel是“包裹”之意 public Destination destination( String s ) { class PDestination implements Destination { // 方法中定义的内部类 private String label; private PDestination( String whereTo ) { label = whereTo; } public String readLabel() { return label; } } return new PDestination( s ); // 只有在方法中才能访问内部类PDestination } public static void main( String[] args ) { Parcel p = new Parcel(); Destination d = p.destination( "Hello" ); ... } } 更进一步,可在任意作用域内定义内部类,举例: public class Parcel { private void internalTracking( boolean b ) { if( b ) { // 局部作用域中定义了内部类,作用域之外不可访问! class TrackingSlip { private String id; TrackingSlip( String s ) { id = s; } String getSlip() { return id; } } } } public void track() { interTracking( true ); } public static void main( String[] args ) { Parcel p = new Parcel(); p.track(); } } 匿名内部类 直观上看,这种内部类没有“名字”,举例: public class Parcel { public Contents contents() { return new Contents() { // 此即匿名内部类!!! private int i = 11; public int value() { return i; } }; // !!!注意这里必须要加分号!!! } public static void main( String[] args ) { Parcel p = new Parcel(); Contents c = p.contents(); } } 若想将外部的参数传到匿名内部类中(典型的如将外部参数用于对匿名内部类中的定义字段进行初始化时)使用的话,该参数必须final,举例: public class Parcel { public Destination destination( final String s ) { // final必须! return new Destination() { private String label = s; public String readLabel() { return label; } }; // 分号必须! } public static void mian( String[] args ) { Parcel p = new Parcel(); Destination d = p.destination("Hello"); } } 匿名内部类中不可能有命名的显式构造器,此时只能使用实例初始化的方式来模仿,举例(当然下面这个例子还反映了匿名内部类如何参与继承): // 基类 --------------------------------------------- abstact class Base() { public Base( int i ) { print( "Base ctor, i = " + i ); } public abstract void f(); } //主类(其中包含了继承上面Base的派生匿名内部类!) ---------------------------------------------- public class AnonymousConstructor { public static Base getBase( int i ) { // 该处参数无需final,因为并未在下面的内部类中直接使用! return new Base(i){ // 匿名内部类 { // 实例初始化语法!!! print("Inside instance initializer"); } public void f() { print( "In anonymous f()" ); } }; // 分号必须! } public static void main( String[] args ) { Base base = getBase(47); base.f(); } } // 输出 ------------------------------------------ Base ctor, i = 47 // 先基类 Inside instance initializer // 再打印派生类 In anonymous f() 匿名内部类 + 工厂模式 = 更加简洁易懂: // Service接口 --------------------------------------------------- interface Service { void method1(); void method2(); } // ServiceFactory接口 --------------------------------------------------- interface ServiceFactory { Service getService(); } // Service接口的实现 --------------------------------------------------- class Implementation1 implements Service { private Implementation1() {} // 构造函数私有 public void method1() { print("Implementation1 method1"); } public void method2() { print("Implementation1 method2"); } public static ServiceFactory factory = new ServiceFactory() { public Service getService() { return new Implementation1(); } }; // 分号必须!!! } class Implementation2 implements Service { private Implementation2() {} public void method1() { print("Implementation2 method1"); } public void method2() { print("Implementation2 method2"); } public static ServiceFactory factory = new ServiceFactory() { public Service getService() { return new Implementation2(); } }; // 分号必须!!! } // 客户端代码 ---------------------------------------------------- public class Factories { public static void serviceConsumer( ServiceFactory fact ) { Service s = fact.getService(); s.method1(); s.method2(); } public static void main( String[] args ) { serviceComsumer( Implementation1.factory ); serviceComsumer( Implementation2.factory ); } } 总结:为什么需要内部类 内部类可以独立地继承自一个接口或者类而无需关注其外围类的实现,这使得扩展类或者接口更加灵活,控制的粒度也可以更细! 注意Java中还有一个细节:虽然Java中一个接口可以继承多个接口,但是一个类是不能继承多个类的!要想完成该特性,此时除了使用内部类来“扩充多重继承机制”,你可能别无选择,举例: class D { } // 普通类 abstract class E { } // 抽象类 class Z extend D { // 外围类显式地完成一部分继承 E makeE() { return new E() { }; // 内部类隐式地完成一部分继承 } } public class MultiImplementation { static void takesD( D d ) { } static void takesE( E e ) { } public static void main( String[] args ) { Z z = new Z(); takesD( z ); takesE( z.makeE() ); } }

优秀的个人博客,低调大师

未来ET大脑将如何打造可编程城市

摘要:在12月20日召开的云栖大会北京峰会上,由阿里云ET大脑架构师陈鹏宇带来了以ET大脑为主题的演讲,从开发者的角度讲述了ET大脑的概念,介绍了ET大脑技术体系架构、数据资源平台、AI服务平台技术体系架构以及对ET大脑未来的发展需求做了介绍。 以下为精彩视频整理: ET大脑技术体系架构 七年前加入阿里巴巴,在这七年里经历了阿里巴巴从传统的BI走向数据智能,走向数据作用于业务的过程。最近三年也见证了ET大脑的技术和产品,从阿里巴巴的内部沉淀,到走向行业去服务于政府和企业。作为一名开发者也是ET大脑最早的使用者和产品的见证者,下面想和大家分享一下什么是ET大脑。 ET大脑是为了帮助政府和企业完成数字化转型的一个创新平台,这个创新平台最核心的要素有三点,一是计算,计算帮助实现了在海量数据下计算的能力,数据中台首次将数据当成一种资源。数据中

优秀的个人博客,低调大师

Hadoop MapReduce编程 API入门系列之FOF(Fund of Fund)

代码 package zhouls.bigdata.myMapReduce.friend; import org.apache.hadoop.io.Text; public class Fof extends Text{//自定义Fof,表示f1和f2关系 public Fof(){//无参构造 super(); } public Fof(String a,String b){//有参构造 super(getFof(a, b)); } public static String getFof(String a,String b){ int r =a.compareTo(b); if(r<0){ return a+"\t"+b; }else{ return b+"\t"+a; } } } package zhouls.bigdata.myMapReduce.friend; import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; import org.apache.hadoop.io.WritableComparable; public class User implements WritableComparable<User>{ //WritableComparable,实现这个方法,要多很多 //readFields是读入,write是写出 private String uname; private int friendsCount; public String getUname() { return uname; } public void setUname(String uname) { this.uname = uname; } public int getFriendsCount() { return friendsCount; } public void setFriendsCount(int friendsCount) { this.friendsCount = friendsCount; }//这一大段的get和set,可以右键,source,产生get和set,自动生成。 public User() {//无参构造 } public User(String uname,int friendsCount){//有参构造 this.uname=uname; this.friendsCount=friendsCount; } public void write(DataOutput out) throws IOException { //序列化 out.writeUTF(uname); out.writeInt(friendsCount); } public void readFields(DataInput in) throws IOException {//反序列化 this.uname=in.readUTF(); this.friendsCount=in.readInt(); } public int compareTo(User o) {//核心 int result = this.uname.compareTo(o.getUname()); if(result==0){ return Integer.compare(this.friendsCount, o.getFriendsCount()); } return result; } } package zhouls.bigdata.myMapReduce.friend; import org.apache.hadoop.io.WritableComparable; import org.apache.hadoop.io.WritableComparator; public class FoFSort extends WritableComparator{ public FoFSort() {//把自定义的User,传进了 super(User.class,true); } public int compare(WritableComparable a, WritableComparable b) {//排序核心 User u1 =(User) a; User u2=(User) b; int result =u1.getUname().compareTo(u2.getUname()); if(result==0){ return -Integer.compare(u1.getFriendsCount(), u2.getFriendsCount()); } return result; } } package zhouls.bigdata.myMapReduce.friend; import org.apache.hadoop.io.WritableComparable; import org.apache.hadoop.io.WritableComparator; public class FoFGroup extends WritableComparator{ public FoFGroup() {//把自定义的User,传进了 super(User.class,true); } public int compare(WritableComparable a, WritableComparable b) {//分组核心 User u1 =(User) a; User u2=(User) b; return u1.getUname().compareTo(u2.getUname()); } } package zhouls.bigdata.myMapReduce.friend; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.DoubleWritable; import org.apache.hadoop.io.IntWritable; import org.apache.hadoop.io.NullWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Job; import org.apache.hadoop.mapreduce.Mapper; import org.apache.hadoop.mapreduce.Reducer; import org.apache.hadoop.mapreduce.lib.input.FileInputFormat; import org.apache.hadoop.mapreduce.lib.input.KeyValueTextInputFormat; import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat; import org.apache.hadoop.util.StringUtils; public class RunJob { // 小明 老王 如花 林志玲 // 老王 小明 凤姐 排序在FoFSort.java // 如花 小明 李刚 凤姐 // 林志玲 小明 李刚 凤姐 郭美美 分组在FoFGroup.java // 李刚 如花 凤姐 林志玲 // 郭美美 凤姐 林志玲 // 凤姐 如花 老王 林志玲 郭美美 public static void main(String[] args) { Configuration config =new Configuration(); // config.set("fs.defaultFS", "hdfs://HadoopMaster:9000"); // config.set("yarn.resourcemanager.hostname", "HadoopMaster"); // config.set("mapred.jar", "C:\\Users\\Administrator\\Desktop\\wc.jar"); // config.set("mapreduce.input.keyvaluelinerecordreader.key.value.separator", ",");//默认分隔符是制表符"\t",这里自定义,如"," if(run1(config)){ run2(config);//设置两个run,即两个mr。 } } public static void run2(Configuration config) { try { FileSystem fs =FileSystem.get(config); Job job =Job.getInstance(config); job.setJarByClass(RunJob.class); job.setJobName("fof2"); job.setMapperClass(SortMapper.class); job.setReducerClass(SortReducer.class); job.setSortComparatorClass(FoFSort.class); job.setGroupingComparatorClass(FoFGroup.class); job.setMapOutputKeyClass(User.class); job.setMapOutputValueClass(User.class); job.setInputFormatClass(KeyValueTextInputFormat.class); // //设置MR执行的输入文件 // FileInputFormat.addInputPath(job, new Path("hdfs://HadoopMaster:9000/f1")); // // //该目录表示MR执行之后的结果数据所在目录,必须不能存在 // Path outputPath=new Path("hdfs://HadoopMaster:9000/out/f2"); //设置MR执行的输入文件 FileInputFormat.addInputPath(job, new Path("./out/f1")); //该目录表示MR执行之后的结果数据所在目录,必须不能存在 Path outputPath=new Path("./out/f2"); if(fs.exists(outputPath)){ fs.delete(outputPath, true); } FileOutputFormat.setOutputPath(job, outputPath); boolean f =job.waitForCompletion(true); if(f){ System.out.println("job 成功执行"); } } catch (Exception e) { e.printStackTrace(); } } public static boolean run1(Configuration config) { try { FileSystem fs =FileSystem.get(config); Job job =Job.getInstance(config); job.setJarByClass(RunJob.class); job.setJobName("friend"); job.setMapperClass(FofMapper.class); job.setReducerClass(FofReducer.class); job.setMapOutputKeyClass(Fof.class); job.setMapOutputValueClass(IntWritable.class); job.setInputFormatClass(KeyValueTextInputFormat.class); // FileInputFormat.addInputPath(job, new Path("hdfs://HadoopMaster:9000/friend/friend.txt"));//下有friend.txt // // Path outpath =new Path("hdfs://HadoopMaster:9000/out/f1"); FileInputFormat.addInputPath(job, new Path("./data/friend/friend.txt"));//下有friend.txt Path outpath =new Path("./out/f1"); if(fs.exists(outpath)){ fs.delete(outpath, true); } FileOutputFormat.setOutputPath(job, outpath); boolean f= job.waitForCompletion(true); return f; } catch (Exception e) { e.printStackTrace(); } return false; } static class FofMapper extends Mapper<Text, Text, Fof, IntWritable>{ protected void map(Text key, Text value, Context context) throws IOException, InterruptedException { String user =key.toString(); String[] friends =StringUtils.split(value.toString(), '\t'); for (int i = 0; i < friends.length; i++) { String f1 = friends[i]; Fof ofof =new Fof(user, f1); context.write(ofof, new IntWritable(0)); for (int j = i+1; j < friends.length; j++) { String f2 = friends[j]; Fof fof =new Fof(f1, f2); context.write(fof, new IntWritable(1)); } } } } static class FofReducer extends Reducer<Fof, IntWritable, Fof, IntWritable>{ protected void reduce(Fof arg0, Iterable<IntWritable> arg1, Context arg2) throws IOException, InterruptedException { int sum =0; boolean f =true; for(IntWritable i: arg1){ if(i.get()==0){ f=false; break; }else{ sum=sum+i.get(); } } if(f){ arg2.write(arg0, new IntWritable(sum)); } } } static class SortMapper extends Mapper<Text, Text, User, User>{ protected void map(Text key, Text value, Context context) throws IOException, InterruptedException { String[] args=StringUtils.split(value.toString(),'\t'); String other=args[0]; int friendsCount =Integer.parseInt(args[1]); context.write(new User(key.toString(),friendsCount), new User(other,friendsCount)); context.write(new User(other,friendsCount), new User(key.toString(),friendsCount)); } } static class SortReducer extends Reducer<User, User, Text, Text>{ protected void reduce(User arg0, Iterable<User> arg1, Context arg2) throws IOException, InterruptedException { String user =arg0.getUname(); StringBuffer sb =new StringBuffer(); for(User u: arg1 ){ sb.append(u.getUname()+":"+u.getFriendsCount()); sb.append(","); } arg2.write(new Text(user), new Text(sb.toString())); } } 本文转自大数据躺过的坑博客园博客,原文链接:http://www.cnblogs.com/zlslch/p/6166095.html,如需转载请自行联系原作者

资源下载

更多资源
Mario

Mario

马里奥是站在游戏界顶峰的超人气多面角色。马里奥靠吃蘑菇成长,特征是大鼻子、头戴帽子、身穿背带裤,还留着胡子。与他的双胞胎兄弟路易基一起,长年担任任天堂的招牌角色。

Nacos

Nacos

Nacos /nɑ:kəʊs/ 是 Dynamic Naming and Configuration Service 的首字母简称,一个易于构建 AI Agent 应用的动态服务发现、配置管理和AI智能体管理平台。Nacos 致力于帮助您发现、配置和管理微服务及AI智能体应用。Nacos 提供了一组简单易用的特性集,帮助您快速实现动态服务发现、服务配置、服务元数据、流量管理。Nacos 帮助您更敏捷和容易地构建、交付和管理微服务平台。

Spring

Spring

Spring框架(Spring Framework)是由Rod Johnson于2002年提出的开源Java企业级应用框架,旨在通过使用JavaBean替代传统EJB实现方式降低企业级编程开发的复杂性。该框架基于简单性、可测试性和松耦合性设计理念,提供核心容器、应用上下文、数据访问集成等模块,支持整合Hibernate、Struts等第三方框架,其适用范围不仅限于服务器端开发,绝大多数Java应用均可从中受益。

Rocky Linux

Rocky Linux

Rocky Linux(中文名:洛基)是由Gregory Kurtzer于2020年12月发起的企业级Linux发行版,作为CentOS稳定版停止维护后与RHEL(Red Hat Enterprise Linux)完全兼容的开源替代方案,由社区拥有并管理,支持x86_64、aarch64等架构。其通过重新编译RHEL源代码提供长期稳定性,采用模块化包装和SELinux安全架构,默认包含GNOME桌面环境及XFS文件系统,支持十年生命周期更新。

用户登录
用户注册
修改密码
忘记密码